﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;
using Windows.Foundation;
using Windows.Graphics.Printing;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.System;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using Bing.Maps;
using com.IronOne.BoardPACWinApp.Common;
using com.IronOne.BoardPACWinApp.Helpers;
using com.IronOne.BoardPACWinApp.View.UserControl;
using com.IronOne.BoardPACWinApp.ViewModel;
using com.IronOne.BoardPACWinAppBO.Agenda;
using com.IronOne.BoardPACWinAppBO.General;
using com.IronOne.BoardPACWinAppBO.Meeting;
using com.IronOne.BoardPACWinAppBO.Paper;
using com.IronOne.BoardPACWinAppBO.Sync;
using com.IronOne.BoardPACWinAppService.Agenda;
using com.IronOne.BoardPACWinAppService.Auth;
using com.IronOne.BoardPACWinAppService.Comment;
using com.IronOne.BoardPACWinAppService.Meeting;
using com.IronOne.BoardPACWinAppService.Sync;
using com.IronOne.BoardPACWinAppUtil.Enums;
using com.IronOne.BoardPACWinAppUtil.Util;
using CompleteReader.Data;
using CompleteReader.Settings;
using GalaSoft.MvvmLight.Messaging;
using pdftron.PDF;
using pdftron.PDF.Annots;
using pdftron.PDF.Tools;
using pdftron.PDF.Tools.Controls;
using pdftron.SDF;
using Action = pdftron.PDF.Action;
using Convert = System.Convert;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace com.IronOne.BoardPACWinApp.View.Page
{
    /// <summary>
    ///     A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class AgendaPage
    {
        public AgendaPage()
        {
            try
            {
                InitializeComponent();
                NavigationHelper = new NavigationHelper(this);

                _asm = new AppSettingsManager();
                _agendaService = new AgendaService();
                _dialogService = new DialogService();
                _authService = new AuthService();
                _syncService = new SyncService();
                _navigationService = new NavigationService();
                _commentService = new CommentService();
                _meetingService = new MeetingService();

                ContentDialog.GetPaperApprovalCommentEvt += (GetPaperApprovalComment);
                MeetingNoteDialogUserControl.GetMeetingNoteEvt += (GetMeetingNote);
                PaperInfoUserControl.ClosePaperInfoEvt += (ClosePaperInfo);

                _dataTransferManager = DataTransferManager.GetForCurrentView();
                _dataTransferManager.DataRequested += DataRequested;

                if (_asm.GetAppBarPinnedStatus())
                    PinnedAppBarButton.IsChecked = true;

                #region PDFTron

                _pdfViewCtrl = new PDFViewCtrl();
                PdfViewCtrlBorder.Child = _pdfViewCtrl;

                _pdfViewCtrl.SetZoomLimits(ZoomLimitMode.e_zoom_limit_relative, 0.1, 20); // Double size 3 times.

                _pdfViewCtrl.SetProgressiveRendering(true);
                _pdfViewCtrl.SetPageRefViewMode(PDFViewCtrlPageViewMode.e_fit_width);
                _pdfViewCtrl.SetPageViewMode(_pdfViewCtrl.GetPageRefViewMode());

                _pdfViewCtrl.SetupThumbnails(false, true, true, 0, 100 * 1024 * 1024, 0.1);
                _pdfViewCtrl.SetPagePresentationMode(PDFViewCtrlPagePresentationMode.e_single_continuous);

                Loaded += ViewerPage_Loaded;
                _toolManager = new ToolManager(_pdfViewCtrl)
                {
                    EnablePopupMenuOnLongPress = false,
                    UseSmallPageNumberIndicator = false
                };
                PageNumberBorder.Child = _toolManager.PageNumberIndicator;

                OutlineDialog.PDFViewCtrl = _pdfViewCtrl;
                QuickSettings.PDFViewCtrl = _pdfViewCtrl;
                AnnotationToolbarDialog.ToolManager = _toolManager;
                FindTextDialog.PDFViewCtrl = _pdfViewCtrl;

                _pdfViewCtrl.OnPageNumberChanged += PDFViewCtrl_OnPageNumberChanged;

                SetPagePresentationMode();
                SetNightMode();

                #endregion
            }
            catch (Exception)
            {
            }
        }

        public NavigationHelper NavigationHelper { get; private set; }

        protected override async void HandleMessages(NotificationMessage<MessageDataModel> mdm)
        {
            try
            {
                base.HandleMessages(mdm);
                await BasePage.GetInstance().HandleMessages(mdm);

                if (mdm.Notification.Equals(MessageCodes.SYNC_DATA_DOWNLOAD_SUCCESS))
                {
                    await WriteMemberAttendanceToLogTable();
                }

                if (mdm.Notification.Equals(MessageCodes.SYNC_UPDATED_DATA))
                {
                    var sudm = (SyncUpdatedDataModel)mdm.Content.MessageData;
                    if (sudm.Meetings != null && sudm.Meetings.Count > 0)
                    {
                        //NOTE: Agenda data update happens in VM

                        #region Update Meeting Info, Member and Individual Attendance

                        var mModel =
                            sudm.Meetings.FirstOrDefault(x => x.MeetingId == OrgAgendaModel.SelectedMeeting.MeetingId);
                        if (mModel != null)
                        {
                            await
                                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                    async () =>
                                    {
                                        //NOTE: if you want update orgAgendaModel as well.
                                        //Since these components are not MVVM UI's are manually gets updated.
                                        if (mModel.MeetingType == 1) // Meeting == 0  |  Circular == 1
                                            mModel.MeetingName = mModel.MeetingName.ToLower();
                                        else
                                            mModel.MeetingName = mModel.MeetingName.ToLower();

                                        //Suren mvvm
                                        //MeetingNameTextBlock.Text = mModel.MeetingName;
                                        OrgAgendaModel.SelectedMeeting.MeetingName = mModel.MeetingName;

                                        if (OrgAgendaModel.SelectedMeeting.IsTentative == 1)
                                        {
                                            //Suren mvvm
                                            //DateTextBlock.Text = "date to be notified";
                                            OrgAgendaModel.SelectedMeeting.DateTimeDisplayText = "date to be notified";
                                        }
                                        else
                                        {
                                            string tFormat = Utility.GetTimeFormat();
                                            var start = DateTime.Parse(mModel.StartTime).ToString(tFormat);
                                            var end = DateTime.Parse(mModel.EndTime).ToString(tFormat);
                                            mModel.DateDisplayText =
                                                Utility.GetDate(mModel.Date).Date.ToString(Global.DateFormat);
                                            //Suren mvvm
                                            //DateTextBlock.Text = mModel.DateDisplayText + "   " + start + " to " + end;
                                            OrgAgendaModel.SelectedMeeting.DateTimeDisplayText = mModel.DateDisplayText + "   " + start + " to " + end;
                                        }

                                        //Meeting / Circular Info Update
                                        MeetingInfoDisplay(mModel);

                                        //Map Update
                                        OrgAgendaModel.SelectedMeeting = mModel;
                                        LoadMap(MyMap);
                                        LoadMap(MyMapLarge);

                                        //Member Attendance
                                        if (!IsParticipantsListUpdated)
                                        {
                                            var list =
                                                await _agendaService.GetParticipantsListForMeeting(mModel.MeetingId);
                                            var memebrs = new ObservableCollection<MemberModel>(list);
                                            LoadParticipantsListViewViaSync(memebrs);
                                        }

                                        //Individual Attendance
                                        await GetIndividualPartcipStatusFromLogTable();
                                    });
                        }

                        #endregion
                    }
                    if (sudm.IsNewOrUpdatedCategories || sudm.IsNewOrUpdatedSubCategories)
                    {
                        //Update category and sub category short names
                        var temp =
                            await
                                _agendaService.GetSelectedCategoryAndSubCategory(
                                    OrgAgendaModel.SelectedCategory.CategoryId,
                                    OrgAgendaModel.SelectedSubCategory.SubCategoryId);
                        OrgAgendaModel.SelectedCategory = temp.SelectedCategory;
                        OrgAgendaModel.SelectedSubCategory = temp.SelectedSubCategory;

                        //Suren mvvm
                        //CategoryShortNameTextBlock.Text = OrgAgendaModel.SelectedCategory.ShortName.ToLower();
                        //Suren mvvm
                        //SubCategoryShortNameTextBlock.Text = OrgAgendaModel.SelectedSubCategory.ShortName.ToLower();
                    }
                }

                if (mdm.Notification.Equals(MessageCodes.SEARCH_FLYOUT))
                {
                    #region Animate

                    var moveSb = new Storyboard();
                    var moveTransform = new TranslateTransform();
                    SearchFlyout.RenderTransform = moveTransform;
                    var duration = new Duration(TimeSpan.FromSeconds(0.3));
                    var myDoubleAnimationX = new DoubleAnimation();
                    var ease = new CubicEase { EasingMode = EasingMode.EaseOut };
                    myDoubleAnimationX.EasingFunction = ease;
                    myDoubleAnimationX.Duration = duration;
                    myDoubleAnimationX.From = (int)(Window.Current.Bounds.Width * 0.3);
                    myDoubleAnimationX.To = 0;
                    moveSb.Children.Add(myDoubleAnimationX);
                    Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                    Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                    moveSb.Begin();

                    AgendaSearchSrhbox.Focus(FocusState.Programmatic);

                    if (BottomAppBar != null && !BottomAppBar.IsSticky) BottomAppBar.IsOpen = false;
                    if (TopAppBar != null) TopAppBar.IsOpen = false;

                    #endregion
                }
            }
            catch (Exception)
            {
            }
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);
                NavigationHelper.OnNavigatedTo(e);

                Global.IsOnAgendaPage = true;
                _isSaveOrgAnnotationFile = true;
                IsLandscape = true;
                IsPortrait = true;

                AnnotationShareUserControl.OriginalPaperLoadingButtonClickedEvent += OriginalPaperLoading_ButtonClick;
                AnnotationShareUserControl.SentPapersButtonClickedEvent += SentPapers_UserControlButtonClick;
                AnnotationShareUserControl.ReceivedPapersButtonClickedEvent += ReceivedPapers_UserControlButtonClick;

                #region PDFTron

                QuickSettings.PresentationModeChanged += QuickSettings_PresentationModeChanged;
                QuickSettings.NightModeChanged += QuickSettings_NightModeChanged;
                QuickSettings.RotateClockwiseRequested += QuickSettings_RotateClockwiseRequested;
                QuickSettings.ThumbnailViewRequested += QuickSettings_ThumbnailViewRequested;
                _pdfViewCtrl.KeyDown += PDFViewCtrl_KeyDown;
                _pdfViewCtrl.IsEnabledChanged += PDFViewCtrl_IsEnabledChanged;

                // printing
                _pdfPrintManager = PDFPrintManager.GetInstance();

                var loader = ResourceLoader.GetForCurrentView("Printing");
                //new Windows.ApplicationModel.Resources.ResourceLoader();
                _pdfPrintManager.SetResourceLoader(loader);

                // standard options
                _pdfPrintManager.AddStandardPrintOption(StandardPrintTaskOptions.MediaSize);
                _pdfPrintManager.AddStandardPrintOption(StandardPrintTaskOptions.Orientation);

                // PDFTron options
                _pdfPrintManager.AddUserOptionAnnotations();
                _pdfPrintManager.AddUserOptionAutoRotate();
                _pdfPrintManager.AddUserOptionPageRange();

                #endregion

                OrgAgendaModel = e.Parameter as AgendaModel;
                SearchFlyout.Opacity = 0;
                SearchFlyout.Visibility = Visibility.Visible;

                if (OrgAgendaModel != null)
                {
                    OrgAgendaModel.SelectedMeeting.MeetingName = OrgAgendaModel.SelectedMeeting.MeetingName.ToLower();
                    OrgAgendaModel.SelectedCategory.ShortName = OrgAgendaModel.SelectedCategory.ShortName.ToLower();
                    OrgAgendaModel.SelectedSubCategory.ShortName =
                        OrgAgendaModel.SelectedSubCategory.ShortName.ToLower();

                    //If Circular then display only the date
                    OrgAgendaModel.SelectedMeeting.DateTimeDisplayText = OrgAgendaModel.SelectedMeeting.DateDisplayText;

                    if (OrgAgendaModel.SelectedMeeting.MeetingType == (int)MeetingType.Meeting)
                    {
                        if (OrgAgendaModel.SelectedMeeting.IsTentative == 1)
                        {
                            OrgAgendaModel.SelectedMeeting.DateTimeDisplayText = "date to be notified";
                        }
                        else
                        {
                            var tFormat = Utility.GetTimeFormat();
                            var start = DateTime.Parse(OrgAgendaModel.SelectedMeeting.StartTime).ToString(tFormat);
                            var end = DateTime.Parse(OrgAgendaModel.SelectedMeeting.EndTime).ToString(tFormat);
                            var date = OrgAgendaModel.SelectedMeeting.DateDisplayText;
                            OrgAgendaModel.SelectedMeeting.DateTimeDisplayText = date + "   " + start + " to " + end;
                        }
                    }

                    var list =
                        await _agendaService.GetParticipantsListForMeeting(OrgAgendaModel.SelectedMeeting.MeetingId);
                    OrgAgendaModel.ParticipantsList = new ObservableCollection<MemberModel>(list);
                    await LoadParticipantsListView(OrgAgendaModel.ParticipantsList);

                    MeetingInfoUimanipulation(OrgAgendaModel.SelectedMeeting);

                    OrgAgendaModel.IndividualParticipationStatusList =
                        Enum.GetValues(typeof(BoardMemberIndividualParticipationStatus))
                            .Cast<BoardMemberIndividualParticipationStatus>()
                            .Select(x => x.ToString())
                            .ToList();

                    //MemberDetails used in meeting info view
                    var memId = Convert.ToInt32(OrgAgendaModel.SelectedMeeting.MeetingOrganizer);
                    OrgAgendaModel.MemberDetails = list.Find(x => x.MemberId == memId);

                    DataContext = OrgAgendaModel;

                    //TODO: check this condition MeetingOrganizer is null is handled now, but 3.14 onwards no need to?  (check above, same condition available)
                    if (OrgAgendaModel.SelectedMeeting.MeetingType == (int)MeetingType.Meeting)
                    {
                        var duration =
                            await
                                _authService.GetSettingValueBySettingName(DatabaseType.UserDb,
                                    ApplicationConstants.UserDbSettingNames.MemberPresenceUpdateInterval);
                        var durationToBlockParticipantsList = Convert.ToInt32(duration);

                        DisplayTimerForParticipantsList(durationToBlockParticipantsList);

                        await GetIndividualPartcipStatusFromLogTable();

                        LoadMap(MyMap);
                    }

                    AgendaGrid.DataContext = new TreeViewPageViewModel(OrgAgendaModel.SelectedMeeting.MeetingId,
                        GlobalSelectdAgendaItem);
                    SearchFlyout.DataContext = AgendaGrid.DataContext;

                    DisplayInitialView();
                    if (OrgAgendaModel != null && GlobalSelectdAgendaItem != null &&
                        (OrgAgendaModel.SelectedMeeting.MeetingId == GlobalSelectdAgendaItem.MeetingId))
                    {
                        //This means comes back to same meeting again. So load where it was before
                        //NOTE: VersionId need to be updated realtime otherwise errors occur
                        var paperModel = await _agendaService.GetPaperById(GlobalSelectdAgendaItem.Id);
                        GlobalSelectdAgendaItem.VersionId = paperModel.VersionId;
                        //NOTE: Add anything else which need to be updated realtime

                        await CreateAnnotatedVersionsMenuFlyOut();
                        await LoadPaperCommon(true, false);
                    }
                }

                SearchFlyout.Opacity = 100;

                #region MeetingNotes button On/Off

                var enableNotePadToBm =
                    await
                        _authService.GetSettingValueBySettingName(DatabaseType.UserDb,
                            ApplicationConstants.UserDbSettingNames.EnableNotePadToBM);
                if (!Global.IsBoardSecrartary && enableNotePadToBm != null && Convert.ToInt16(enableNotePadToBm) == 0)
                {
                    MeetingNoteButton.Visibility = Visibility.Collapsed;
                }

                #endregion
            }
            catch (Exception)
            {
            }
            finally
            {
                PgbPage.Visibility = Visibility.Collapsed;
            }
        }

        public async Task LoadPaperCommon(bool isWithAnnotationFile, bool isDownloadIfPaperNotExist)
        {
            #region Load previously opened paper

            if (OrgAgendaModel != null && GlobalSelectdAgendaItem != null &&
                (OrgAgendaModel.SelectedMeeting.MeetingId == GlobalSelectdAgendaItem.MeetingId))
            {
                //Suren - removed from here and put on top
                //orgAgendaModel.IsBoardSecretary = (orgAgendaModel.SelectedMeeting.Actions.Contains("UpdateMeetingPresence_XML") ? true : false);

                //NOTE: DiscussionItems dont have papers but user can comment on it
                if (GlobalSelectdAgendaItem.DocType != null &&
                    (byte)GlobalSelectdAgendaItem.DocType == (byte)DocumentType.DiscussionItem)
                {
                    DisplayDiscussionPaperView();

                    if (Global.IsBoardSecrartary)
                    {
                        await CreateApprovalMenuFlyOut();
                    }
                }
                else
                {
                    #region Paper Download or Load to View

                    var docTypeName = BasePage.GetInstance().GetDocTypeName(GlobalSelectdAgendaItem.DocType);
                    var imdlg = new InputMessageDialog(docTypeName + "loading", Visibility.Collapsed,
                        Visibility.Collapsed,
                        true);
                    imdlg.ShowAsync();

                    if (GlobalSelectdAgendaItem.DocType != null)
                    {
                        var file =
                            await
                                _agendaService.GetPdfDocument(GlobalSelectdAgendaItem.Id,
                                    GlobalSelectdAgendaItem.MeetingId,
                                    (byte)GlobalSelectdAgendaItem.DocType, GlobalSelectdAgendaItem.VersionId);
                        try
                        {
                            if (file == null)
                            {
                                if (isDownloadIfPaperNotExist)
                                {
                                    imdlg.HideAsync();
                                    await DownloadPaper();
                                    return;
                                }

                                imdlg.HideAsync();
                                DisplayInitialView();
                                await _dialogService.ShowMessage(ResourceHandler.Get("err_102"));
                            }
                            else
                            {
                                await CreateApprovalMenuFlyOut();

                                if (GlobalSelectdAgendaItem.DocType == (byte)DocumentType.AudioVideo)
                                {
                                    await LoadMediaToViewer(file);
                                }
                                else
                                {
                                    bool result = await LoadPdfDocumentToViewer(file, imdlg);
                                    if (!result) return;

                                    DisplaySmallPaperView();
                                }

                                imdlg.HideAsync();
                            }
                        }
                        catch (Exception)
                        {
                            if (imdlg != null) imdlg.HideAsync();
                            DisplayInitialView();
                        }
                    }

                    #endregion

                    //If pdfviewcontrol is currently loaded, have set member approval stamp. Since stamp is not an annotation in 
                    //pdftron every time when paper loading have to set stamp manually.
                    var givenBmApprovalFromDb = await _agendaService.GetAgendaItemApproval(GlobalSelectdAgendaItem.Id);
                    PaperStatus = Global.IsBoardSecrartary
                        ? ((PaperStatus)givenBmApprovalFromDb.Item1).ToString()
                        : ((DecisionStatus)givenBmApprovalFromDb.Item1).ToString();

                    if (givenBmApprovalFromDb.Item1 != 0) //Skip pending status
                    {
                        try
                        {
                            await
                                BasePage.GetInstance()
                                    .SetApprovalStamp(_param.Doc, _pdfViewCtrl, PaperStatus, GlobalSelectdAgendaItem);
                        }
                        catch (Exception)
                        {
                            //In case document didn't load correctly
                        }
                    }
                }
                await LoadBookmarks();
            }
            else //Load as default view
            {
                GlobalSelectdAgendaItem = null;
                DisplayInitialView();
            }

            if (isWithAnnotationFile)
            {
                await ImportAnnotations();
            }

            #endregion
        }

        protected override async void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedFrom(e);
                NavigationHelper.OnNavigatedFrom(e);

                Global.IsOnAgendaPage = false;

                await WriteMemberAttendanceToLogTable();

                #region PDFTron

                await ExportAnnotations();

                /*await CloseDoc();
                this.ToolManager.Dispose();
                PDFDoc doc = PDFViewCtrl.GetDoc();
                PDFViewCtrl.CloseDoc();
                PDFViewCtrl.FreeResources();
                PDFViewCtrl.Dispose();

                _PDFPrintManager.UnRegisterForPrintingContract();
                if (doc != null)
                {
                    doc.Dispose();
                }*/

                QuickSettings.PresentationModeChanged -= QuickSettings_PresentationModeChanged;
                QuickSettings.NightModeChanged -= QuickSettings_NightModeChanged;
                QuickSettings.RotateClockwiseRequested -= QuickSettings_RotateClockwiseRequested;
                QuickSettings.ThumbnailViewRequested -= QuickSettings_ThumbnailViewRequested;
                _pdfViewCtrl.KeyDown -= PDFViewCtrl_KeyDown;
                _pdfViewCtrl.IsEnabledChanged -= PDFViewCtrl_IsEnabledChanged;

                if (_thumbSliderAppBar != null)
                {
                    _thumbSliderAppBar.Content = null;
                }

                _pdfPrintManager.UnRegisterForPrintingContract();

                #endregion

                //Free the resources allocated for media
                MediaElementForAgenda.Source = null;
                MediaElementForAgenda = null;

                //Timer to auto save annotations
                if (_dispatcherTimerForAutoSave != null)
                {
                    _dispatcherTimerForAutoSave.Stop();
                    _dispatcherTimerForAutoSave.Tick -= (s, args) => DispatcherTimer_TickForAutoSave();
                }
            }
            catch (Exception)
            {
            }
        }

        private void ViewerPage_Loaded(object sender, RoutedEventArgs e)
        {
            _thumbSliderAppBar = BottomAppBar;
            _topAppBar = TopAppBar;
        }


        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            try
            {
                if (e.NewSize.Width < 768)
                {
                    NotSupportedItemGrid.Visibility =  Visibility.Visible;
                    return;
                }

                NotSupportedItemGrid.Visibility = Visibility.Collapsed;

                if (e.NewSize.Width < 1366)
                {
                    RefreshPortraitView();
                    return;
                }

                RefreshLandscapeView();
                return;

                NotSupportedItemGrid.Visibility = Visibility.Collapsed;

                _pdfViewCtrl.VerticalAlignment = VerticalAlignment.Top;
                var ori = ApplicationView.GetForCurrentView().Orientation;
                switch (ori)
                {
                    case ApplicationViewOrientation.Landscape:
                        RefreshLandscapeView();
                        break;

                    case ApplicationViewOrientation.Portrait:

                        RefreshPortraitView();
                        break;
                }
                

                /*if (MiddleSliderBtn.Visibility == Visibility.Visible && IsCollapsed)
                {

                }
                else
                {
                    _pdfViewCtrl.Width = (e.NewSize.Width - ((e.NewSize.Width * 1.35) / 2.35)) - 50;
                    _collapsedWidth = _pdfViewCtrl.Width;
                }*/

                //SetPagePresentationMode();

                //_pdfViewCtrl.Background = new SolidColorBrush(Colors.Gray);

                //_pdfViewCtrl.Width = (e.NewSize.Width - ((e.NewSize.Width * 1.35) / 2.35)) - 50;
                //NOTE: 50 will added as a little margin
                //_collapsedWidth = _pdfViewCtrl.Width;       
            }
            catch (Exception)
            {
            }     
        }
        
        private void RefreshLandscapeView()
        {
            try
            {
                if (!IsLandscape) return;
                IsLandscape = false;
                IsPortrait = true;

                ParticipationStatTxt.Text = "Participation status";

                #region AppBar
                //TopAppBar
                AppBarLogoutButton.IsCompact = false;
                AppBarButtonSearch.IsCompact = false;
                AppBarToggleButtonBookmark.IsCompact = false;
                AppBarButtonViewPage.IsCompact = false;
                AppBarButtonViewMode.IsCompact = false;
                AppBarButtonOutline.IsCompact = false;
                AppBarButtonAnnotateVersions.IsCompact = false;
                AppBarButtonSharing.IsCompact = false;
                AppBarButtonEdit.IsCompact = false;

                //BottomAppBar
                MeetingsButton.IsCompact = false;
                AgendaSearchButton.IsCompact = false;
                MeetingCommentButton.IsCompact = false;
                PastPapersButton.IsCompact = false;
                MeetingNoteButton.IsCompact = false;
                PaperCommentsButton.IsCompact = false;
                ApprovalButton.IsCompact = false;
                SharePaperButton.IsCompact = false;
                InfoButton.IsCompact = false;
                PinnedAppBarButton.IsCompact = false;
                #endregion

                #region Page titles
                BackButtonL.Visibility = Visibility.Visible;
                BackButtonP.Visibility = Visibility.Collapsed;
                PageHeaderTextL.Visibility = Visibility.Visible;
                PageHeaderTextP.Visibility = Visibility.Collapsed;
                PageSubHeaderTextL.Visibility = Visibility.Visible;
                PageSubHeaderTextP.Visibility = Visibility.Collapsed;
                PageSubHeaderTextL1.Visibility = Visibility.Visible;
                PageSubHeaderTextP1.Visibility = Visibility.Collapsed;
                PageSubHeaderTextL2.Visibility = Visibility.Visible;
                PageSubHeaderTextP2.Visibility = Visibility.Collapsed;
                #endregion

                if (DiscussionItemGrid.Visibility == Visibility.Visible)
                {
                    //ok
                }
                if (WidgetsGrid.Visibility == Visibility.Visible)
                {
                    #region WidgetsGrid
                    StkPnl1.Visibility = Visibility.Visible;
                    GridW1.Visibility = Visibility.Visible;
                    StkPnl2.Visibility = Visibility.Visible;
                    ParticipantsListView.Visibility = Visibility.Visible;
                    WidgetSwitch.Visibility = Visibility.Collapsed;

                    Grid.SetColumn(StkPnl2, 2);
                    Grid.SetColumnSpan(StkPnl2, 2);
                    Grid.SetColumn(ParticipantsListView, 2);
                    Grid.SetColumnSpan(ParticipantsListView, 2);

                    Grid.SetColumnSpan(StkPnl1, 2);
                    Grid.SetColumnSpan(GridW1, 2);
                    #endregion
                }
                if (VideoItemsGrid.Visibility == Visibility.Visible)
                {

                }
                if (BoardPaperGrid.Visibility == Visibility.Visible)
                {

                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        
        private void RefreshPortraitView()
        {
            try
            {
                if (!IsPortrait) return;
                IsPortrait = false;
                IsLandscape = true;

                ParticipationStatTxt.Text = "Status";

                #region AppBar
                //TopAppBar
                AppBarLogoutButton.IsCompact = true;
                AppBarButtonSearch.IsCompact = true;
                AppBarToggleButtonBookmark.IsCompact = true;
                AppBarButtonViewPage.IsCompact = true;
                AppBarButtonViewMode.IsCompact = true;
                AppBarButtonOutline.IsCompact = true;
                AppBarButtonAnnotateVersions.IsCompact = true;
                AppBarButtonSharing.IsCompact = true;
                AppBarButtonEdit.IsCompact = true;

                //BottomAppBar
                MeetingsButton.IsCompact = true;
                AgendaSearchButton.IsCompact = true;
                MeetingCommentButton.IsCompact = true;
                PastPapersButton.IsCompact = true;
                MeetingNoteButton.IsCompact = true;
                PaperCommentsButton.IsCompact = true;
                ApprovalButton.IsCompact = true;
                SharePaperButton.IsCompact = true;
                InfoButton.IsCompact = true;
                PinnedAppBarButton.IsCompact = true;
                #endregion

                #region Page titles
                BackButtonL.Visibility = Visibility.Collapsed;
                BackButtonP.Visibility = Visibility.Visible;
                PageHeaderTextL.Visibility = Visibility.Collapsed;
                PageHeaderTextP.Visibility = Visibility.Visible;
                PageSubHeaderTextL.Visibility = Visibility.Collapsed;
                PageSubHeaderTextP.Visibility = Visibility.Visible;
                PageSubHeaderTextL1.Visibility = Visibility.Collapsed;
                PageSubHeaderTextP1.Visibility = Visibility.Visible;
                PageSubHeaderTextL2.Visibility = Visibility.Collapsed;
                PageSubHeaderTextP2.Visibility = Visibility.Visible;
                #endregion

                if (DiscussionItemGrid.Visibility == Visibility.Visible)
                {
                    //ok
                }
                if (WidgetsGrid.Visibility == Visibility.Visible)
                {
                    #region WidgetsGrid
                    StkPnl1.Visibility = Visibility.Collapsed;
                    GridW1.Visibility = Visibility.Collapsed;
                    StkPnl2.Visibility = Visibility.Visible;
                    ParticipantsListView.Visibility = Visibility.Visible;
                    WidgetSwitch.Visibility = Visibility.Visible;

                    Grid.SetColumn(StkPnl2, 0);
                    Grid.SetColumnSpan(StkPnl2, 3);
                    Grid.SetColumn(ParticipantsListView, 0);
                    Grid.SetColumnSpan(ParticipantsListView, 3);

                    Grid.SetColumnSpan(StkPnl1, 3);
                    Grid.SetColumnSpan(GridW1, 3);
                    #endregion
                }
            }
            catch (Exception)
            {
                throw;
            }
        }


        private async void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
        {
            try
            {
                var dataPackage = e.Request.Data;


                if (GlobalSelectdAgendaItem == null || (!_isPaperEmailingAllowed && !_isCommentsEmailingAllowed) ||
                    _param == null || _param.Doc == null)
                    return;

                if (_isPaperEmailingAllowed)
                {
                    dataPackage.Properties.Title = OrgAgendaModel.SelectedMeeting.MeetingName + "_" +
                                                   GlobalSelectdAgendaItem.Name + "_Annotated paper";
                    dataPackage.Properties.Description = "Mail app is recommended for email";
                    dataPackage.Properties.ApplicationName = "BoardPAC";
                    dataPackage.SetHtmlFormat(
                        HtmlFormatHelper.CreateHtmlFormat("<b>Meeting name:</b/><br/>" +
                                                          OrgAgendaModel.SelectedMeeting.MeetingName +
                                                          "<br/><br/><b>Paper name:</b/><br/>" +
                                                          GlobalSelectdAgendaItem.Name));

                    var storageItems = new List<IStorageItem>();
                    var file = await GetEmailReadyPaper();
                    storageItems.Add(file);
                    dataPackage.SetStorageItems(storageItems, true);
                    return;
                }
                if (!_isCommentsEmailingAllowed) return;
                var final = "";
                var contents = "";
                var inc = 1;
                var itr = _pdfDoc.GetPageIterator();

                for (; itr.HasNext(); itr.Next())
                {
                    inc++;
                    var pageStr = "<br/><b>Page " + inc + "</b><br/>";

                    var current = itr.Current();
                    var numAnnots = current.GetNumAnnots();

                    for (var i = 0; i < numAnnots; ++i)
                    {
                        var annot = current.GetAnnot(i);

                        if (annot.IsValid() == false) continue;
                        if (annot.GetType() != typeof(Popup)) continue;
                        contents += annot.GetContents();
                        if (String.IsNullOrWhiteSpace(contents)) continue;
                        contents += "<br/>";
                    }

                    if (!String.IsNullOrWhiteSpace(contents))
                        final += pageStr + contents;
                    contents = "";
                }

                dataPackage.Properties.Title = OrgAgendaModel.SelectedMeeting.MeetingName + "_" +
                                               GlobalSelectdAgendaItem.Name + "_Annotated comments";
                dataPackage.Properties.Description = "Mail app is recommended for email";
                dataPackage.Properties.ApplicationName = "BoardPAC";
                dataPackage.SetHtmlFormat(
                    HtmlFormatHelper.CreateHtmlFormat("<b>Meeting name:</b/><br/>" +
                                                      OrgAgendaModel.SelectedMeeting.MeetingName +
                                                      "<br/><br/><b>Paper name:</b/><br/>"
                                                      + GlobalSelectdAgendaItem.Name +
                                                      "<br/><br/><b>Meeting date:</b/><br/>" +
                                                      OrgAgendaModel.SelectedMeeting.DateDisplayText +
                                                      "<br/><br/><b>" + GlobalSelectdAgendaItem.Name
                                                      + " comments:" + "</b>" + final));
            }
            catch (Exception)
            {
            }
            finally
            {
                _isPaperEmailingAllowed = false;
                _isCommentsEmailingAllowed = false;
            }
        }

        //NOTE: Can't remove this fucntion to a DAO, coz PDFTron dll not available in any DAO.
        private async Task<StorageFile> GetEmailReadyPaper()
        {
            try
            {
                var tempFolder =
                    await
                        StorageFolder.GetFolderFromPathAsync(Path.Combine(ApplicationData.Current.TemporaryFolder.Path));
                var papName = GlobalSelectdAgendaItem.Name + ApplicationConstants.PDFEXT;
                var emailPaper = await tempFolder.CreateFileAsync(papName, CreationCollisionOption.GenerateUniqueName);

                //NOTE: Can't remove this to a DAO, coz PDFTron dll not available in any DAO.
                await _pdfDoc.SaveToNewLocationAsync(emailPaper, SDFDocSaveOptions.e_incremental);

                return await _agendaService.GetEmailReadyPaper(emailPaper.Name);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private async Task ImportAnnotations()
        {
            try
            {
                if (_param == null) return;

                await BasePage.GetInstance().ImportAnnotations(_param.Doc, GlobalSelectdAgendaItem);
                int paperNo = await BasePage.GetInstance().GetCurrentPageOfThePaper(GlobalSelectdAgendaItem.Id, GlobalSelectdAgendaItem.VersionId);
                _pdfViewCtrl.SetCurrentPage(paperNo);
                _pdfViewCtrl.Update();
            }
            catch (Exception)
            {
            }
        }

        private async Task ExportAnnotations()
        {
            try
            {
                if (_param != null && _isSaveOrgAnnotationFile)
                {
                    await BasePage.GetInstance().ExportAnnotations(_param.Doc, GlobalSelectdAgendaItem, _pdfViewCtrl.GetCurrentPage());
                }
            }
            catch (Exception)
            {
            }
        }

        private void pageRoot_Unloaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _asm = null;
                //_agendaService = null;
                _dialogService = null;
                //_authService = null;
                _syncService = null;
                _navigationService = null;
                _commentService = null;
                _meetingService = null;

                ContentDialog.GetPaperApprovalCommentEvt -= (GetPaperApprovalComment);
                MeetingNoteDialogUserControl.GetMeetingNoteEvt -= (GetMeetingNote);
                PaperInfoUserControl.ClosePaperInfoEvt -= (ClosePaperInfo);
                _dataTransferManager.DataRequested -= DataRequested;

                AnnotationShareUserControl.OriginalPaperLoadingButtonClickedEvent -= OriginalPaperLoading_ButtonClick;
                AnnotationShareUserControl.SentPapersButtonClickedEvent -= SentPapers_UserControlButtonClick;
                AnnotationShareUserControl.ReceivedPapersButtonClickedEvent -= ReceivedPapers_UserControlButtonClick;

                if (_mUserControl != null) _mUserControl.ClosePopup();
            }
            catch (Exception)
            {
            }
        }

        #region Variables

        #region Services

        private IDialogService _dialogService;
        private INavigationService _navigationService;
        private readonly IAgendaService _agendaService;
        private readonly IAuthService _authService;
        private ISyncService _syncService;
        private ICommentService _commentService;
        private IMeetingService _meetingService;
        private AppSettingsManager _asm;

        #endregion

        public delegate void AgendaItemForceDownloadDel(PaperDownloadStatuses stat, int agendaItemId);

        public static event AgendaItemForceDownloadDel AgendaItemForceDownloadEvt;
        public static EventHandler AgendaItemClickPaperStatusSideIconEvtHandler;

        public static AgendaModel OrgAgendaModel;
        public static AgendaItem GlobalSelectdAgendaItem;
        public bool IsParticipantsListUpdated;
        public LogDataModel LogModel = new LogDataModel();
        public Dictionary<int, int> AttendanceChanges = new Dictionary<int, int>();

        private DispatcherTimer _dispatcherTimer;
        private DispatcherTimer _dispatcherTimerForAutoSave;
        const int AutoSaveTimeInSec = 10;
        private TimeSpan _diff;
        private int _passwordAttempts = Utility.GetNoOfPasswordAttempts();
        private static TaskCompletionSource<bool> _oTaskCompletionSource;

        private int _initialCmbSelectedIndex = -1;
        private int _loggedInMemberParticipantStat;
        private double _collapsedWidth;
        public bool IsCollapsed;
        public string PaperStatus { get; set; } //Approval status given by BM Or BS for the paper
        private Dictionary<int, string> _bookmarks = new Dictionary<int, string>();
        private const string Page = "Page ";
        private bool _isPaperEmailingAllowed;
        private bool _isCommentsEmailingAllowed;
        private readonly DataTransferManager _dataTransferManager;
        private AnnotationShareUserControl _mUserControl;
        //If opened annot file is not from Original folder app should not save whatever the annot file opened to the Org file.
        //Saving the org file only happens if this is true.
        private bool _isSaveOrgAnnotationFile = true;
        public static bool IsLandscape = true;
        public static bool IsPortrait = true;

        private const string EnableIn = "enable in ";
        private const string DisableIn = "disable in ";
        private const string Redonly = ""; //"readonly";
        private const string Enableed = ""; //"editable"; 

        #endregion

        #region PDFTron

        private readonly PDFViewCtrl _pdfViewCtrl;
        private PDFDoc _pdfDoc;
        private NavigationParameter _param;
        private readonly ToolManager _toolManager;

        private PDFPrintManager _pdfPrintManager;
        private AppBar _thumbSliderAppBar;
        private AppBar _topAppBar;
        private ThumbnailViewer _thumbnailViewer;

        #endregion

        #region PDFTron

        private void PDFViewCtrl_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                if (((bool)e.NewValue))
                {
                    AttachAppBars();
                    AnnotationToolbarDialog.IsEnabled = true;
                    FindTextDialog.IsEnabled = true;
                }
                else
                {
                    AnnotationToolbarDialog.IsEnabled = false;
                    FindTextDialog.IsEnabled = false;
                    DetachAppBars();
                }
            }
            catch (Exception)
            {
            }
        }

        /*private async Task CloseDoc()
        {
            try
            {
                var doc = _pdfViewCtrl.GetDoc();
                _pdfViewCtrl.CloseDoc();

                if (doc != null)
                {
                    await CloseDocAsync(doc);
                }

                _pdfViewCtrl.FreeResources();
                //this.PDFViewCtrl.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
        }*/

        /*private IAsyncAction CloseDocAsync(PDFDoc doc)
        {
            var t = new Task(() => { doc.Dispose(); });
            t.Start();
            return t.AsAsyncAction();
        }*/

        /// <summary>
        ///     2015-07-06
        ///     Bhathiya Dasanayake
        ///     This method will only render the current page annotation. When page number changed this method will call.
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="numPages"></param>
        private void PDFViewCtrl_OnPageNumberChanged(int currentPage, int numPages)
        {
            _pdfViewCtrl.Update();
        }

        private void PDFViewCtrl_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            try
            {
                var state = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Control);
                if ((state & CoreVirtualKeyStates.Down) != CoreVirtualKeyStates.Down) return;
                switch (e.Key)
                {
                    case VirtualKey.F:
                        FindTextDialog.OpenDialog();
                        break;
                }
            }
            catch (Exception)
            {

            }
        }

        private void AgendaGrid_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            try
            {
                var state = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Control);
                if ((state & CoreVirtualKeyStates.Down) != CoreVirtualKeyStates.Down) return;
                switch (e.Key)
                {
                    case VirtualKey.F:
                        OutlineDialog.CloseDialog();

                        var mdm = new MessageDataModel { MessageData = true };
                        var message = new NotificationMessage<MessageDataModel>(mdm, MessageCodes.SEARCH_FLYOUT);
                        Messenger.Default.Send(message);
                        break;
                }
            }
            catch (Exception)
            {
            }
        }

        private IAsyncOperation<PDFDoc> GetPdfDocAsync(IBuffer file)
        {
            try
            {
                var t = new Task<PDFDoc>(() => GetPdfDoc(file));
                t.Start();
                return t.AsAsyncOperation();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private PDFDoc GetPdfDoc(IBuffer file)
        {
            return new PDFDoc(file);
        }

        private void HandlePassword()
        {
            try
            {
                PasswordGrid.Visibility = Visibility.Visible;
                PasswordDialog.Visibility = Visibility.Visible;
                PasswordDialog.SetFocus();
                PasswordDialog.Reset();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void PasswordDialog_PasswordEntered(string password)
        {
            try
            {
                if (password == null)
                {
                    PasswordDialog.Visibility = Visibility.Collapsed;
                    if (_oTaskCompletionSource != null &&
                        _oTaskCompletionSource.Task.Status != TaskStatus.RanToCompletion)
                    {
                        _oTaskCompletionSource.SetResult(false);
                    }
                }
                else
                {
                    if (_pdfDoc.InitStdSecurityHandler(password))
                    {
                        _pdfDoc.InitStdSecurityHandler(password);
                        CommonPaperLoading();
                        PasswordDialog.Visibility = Visibility.Collapsed;
                        _oTaskCompletionSource.SetResult(true);
                    }
                    else
                    {
                        PasswordDialog.NotifyIncorrectPassword();
                        _passwordAttempts--;
                        if (_passwordAttempts == 0)
                            PasswordDialog_PasswordEntered(null);
                        else
                            PasswordDialog.SetFocus();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region PDFTron Flyout Management

        private void FlyoutDialogEnabled()
        {
            TapOverlayGrid.Visibility = Visibility.Visible;
        }

        private void FlyoutDialogDisabled()
        {
            TapOverlayGrid.Visibility = Visibility.Collapsed;
            OutlineDialog.CloseDialog();
        }

        private void TapOverlayGrid_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            FlyoutDialogDisabled();
        }

        #endregion FlyoutManagement

        #region PDFTron Settings

        private void QuickSettings_PresentationModeChanged()
        {
            SetPagePresentationMode();
        }

        private void SetPagePresentationMode()
        {
            CloseAppBars();
            //var oldPresentationMode = _pdfViewCtrl.GetPagePresentationMode();
            //var oldViewMode = _pdfViewCtrl.GetPageViewMode();
            _pdfViewCtrl.SetPagePresentationMode(Settings.PagePresentationMode);
        }

        public void SetButtonsStayDown(bool stayDown)
        {
            AnnotationToolbarDialog.ButtonsStayDown = stayDown;
        }

        private void QuickSettings_NightModeChanged()
        {
            CloseAppBars();
            SetNightMode();
        }

        private void SetNightMode()
        {
            if (Settings.NightMode)
            {
                _pdfViewCtrl.SetColorPostProcessMode(PDFRasterizerColorPostProcessMode.e_postprocess_invert);
                _pdfViewCtrl.Update(true);
            }
            else
            {
                _pdfViewCtrl.SetColorPostProcessMode(PDFRasterizerColorPostProcessMode.e_postprocess_none);
                _pdfViewCtrl.Update(true);
            }
        }

        private void QuickSettings_RotateClockwiseRequested()
        {
            _pdfViewCtrl.RotateClockwise();
        }

        private void QuickSettings_ThumbnailViewRequested()
        {
            CloseAppBars();
            ThumbnailViewGrid.Visibility = Visibility.Visible;
            _pdfViewCtrl.IsEnabled = false;
            _thumbnailViewer = new ThumbnailViewer(_pdfViewCtrl);
            if (Settings.NightMode)
            {
                ThumbnailViewGrid.Background = new SolidColorBrush(Color.FromArgb(255, 50, 50, 50));
                _thumbnailViewer.BlankPageDefaultColor = Colors.Black;
            }
            else
            {
                ThumbnailViewGrid.Background = new SolidColorBrush(Colors.Black);
            }
            _thumbnailViewer.ControlClosed += ThumbnailsViewer_ControlClosed;
            ThumbnailViewGrid.Children.Add(_thumbnailViewer);
        }

        private void ThumbnailsViewer_ControlClosed()
        {
            CloseThumbnailsViewer();
        }

        private void CloseThumbnailsViewer()
        {
            ThumbnailViewGrid.Children.Clear();
            ThumbnailViewGrid.Visibility = Visibility.Collapsed;
            _pdfViewCtrl.IsEnabled = true;
            if (_thumbnailViewer != null)
            {
                _thumbnailViewer.ControlClosed -= ThumbnailsViewer_ControlClosed;
            }
        }

        #endregion Settings

        #region ParticipantsList

        private async Task GetIndividualPartcipStatusFromLogTable()
        {
            try
            {
                var ldm =
                    await
                        _agendaService.GetIndividualPartcipStatusFromLogTable(OrgAgendaModel.SelectedMeeting.MeetingId);
                if (ldm != null)
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        if (!ldm.Data.Contains('#'))
                        {
                            _loggedInMemberParticipantStat = int.Parse(ldm.Data);
                            CmbIndividualParticipationStatus.SelectedIndex = _loggedInMemberParticipantStat;
                            return;
                        }

                        var memberIndividualPresentArr = ldm.Data.Split('#');
                        for (var i = 0; i < memberIndividualPresentArr.Count(); i = i + 2)
                        {
                            if (Global.UserId == int.Parse(memberIndividualPresentArr[i]))
                            {
                                _loggedInMemberParticipantStat = int.Parse(memberIndividualPresentArr[i + 1]);
                            }
                        }
                        CmbIndividualParticipationStatus.SelectedIndex = _loggedInMemberParticipantStat;
                    });
                }
            }
            catch (Exception)
            {
            }
        }

        private void DisplayTimerForParticipantsList(int durationToBlockParticipantsList)
        {
            try
            {
                var meetingStartDate = OrgAgendaModel.SelectedMeeting.Date;
                var meetingStartTime = DateTime.Parse(OrgAgendaModel.SelectedMeeting.StartTime);
                var meetingEndTime = DateTime.Parse(OrgAgendaModel.SelectedMeeting.EndTime);

                var start = meetingStartDate.Date.Add(meetingStartTime.TimeOfDay);
                var end = meetingStartDate.Date.Add(meetingEndTime.TimeOfDay);
                var now = DateTime.Now;

                if (now < start) //Meeting is not started yet
                {
                    _diff = start.Subtract(now);

                    LblMeetingTimerDisplay.Text = Enableed;
                    LblParticipantsTimerDisplay.Text = Redonly;

                    var am = (AgendaModel)ParticipantsListView.DataContext;
                    foreach (var item in am.ParticipantsList)
                    {
                        item.IsParticipationBtnVisible = Visibility.Collapsed;
                        item.StatusColorCode = new SolidColorBrush(Colors.Gray);
                    }
                    ParticipantsListView.DataContext = null;
                    ParticipantsListView.DataContext = am;

                    if (_diff.TotalHours > 1 && Global.IsBoardSecrartary)
                    {
                        LblParticipantsTimerDisplay.Text = EnableIn + "1+ hours";
                        return;
                    }

                    _dispatcherTimer = new DispatcherTimer();
                    _dispatcherTimer.Tick += (s, args) => DispatcherTimer_Tick(durationToBlockParticipantsList);
                    _dispatcherTimer.Interval = new TimeSpan(0, 0, 1); //1 second
                    _dispatcherTimer.Start();
                    return;
                }

                if (now > start && now <= end) //Meeting ongoing
                {
                    CmbIndividualParticipationStatus.IsEnabled = false;
                    LblMeetingTimerDisplay.Text = Redonly;

                    /*AgendaModel am = (AgendaModel)ParticipantsListView.DataContext;
                    foreach (var item in am.ParticipantsList)
                    {
                        item.IsParticipationBtnEnabled = true;
                    }
                    ParticipantsListView.DataContext = null;
                    ParticipantsListView.DataContext = am;*/

                    if (!Global.IsBoardSecrartary)
                        LblParticipantsTimerDisplay.Text = Redonly;
                    else
                        LblParticipantsTimerDisplay.Text = Enableed;

                    //TODO: Track end of the meeting and disable participants list
                    /*diff1 = end.Subtract(now);
                    dispatcherTimer1 = new DispatcherTimer();
                    dispatcherTimer1.Tick += (s, args) => DispatcherTimer1_Tick1();
                    dispatcherTimer1.Interval = new TimeSpan(0, 0, 1); //1 second
                    dispatcherTimer1.Start();*/

                    return;
                }

                if (now >= end) //Meeting ended
                {
                    CmbIndividualParticipationStatus.IsEnabled = false;
                    LblMeetingTimerDisplay.Text = Redonly;

                    if (!Global.IsBoardSecrartary)
                        LblParticipantsTimerDisplay.Text = Redonly;
                    else
                        LblParticipantsTimerDisplay.Text = Enableed;
                }
            }
            catch (Exception)
            {
            }
        }

        private async void DispatcherTimer_TickForAutoSave()
        {
            try
            {
                await ExportAnnotations();
            }
            catch (Exception)
            {
            }
        }

        private void DispatcherTimer_Tick(int durationToBlockParticipantsList)
        {
            try
            {
                //Meeting Info
                var val1 = (durationToBlockParticipantsList * 2) - 1;
                var val2 = durationToBlockParticipantsList - 1;
                if (((int)_diff.TotalMinutes) <= val1 && ((int)_diff.TotalMinutes) > val2)
                //This means between less than 20 mins and greater than 10 mins
                {
                    var ts = _diff.Subtract(new TimeSpan(0, durationToBlockParticipantsList, 0));
                    LblMeetingTimerDisplay.Text = DisableIn + ts.Minutes.ToString("0") + ":" + ts.Seconds.ToString("00");
                    if (Global.IsBoardSecrartary)
                        LblParticipantsTimerDisplay.Text = EnableIn + ts.Minutes.ToString("0") + ":" +
                                                           ts.Seconds.ToString("00");
                }

                _diff = _diff.Subtract(new TimeSpan(0, 0, 1));

                //Participants Info
                if (((int)_diff.TotalMinutes) <= val2) //This means 10 mins
                {
                    //Meeting Info
                    CmbIndividualParticipationStatus.IsEnabled = false;
                    LblMeetingTimerDisplay.Text = "";

                    //Participants Info

                    #region MyRegion

                    if (Global.IsBoardSecrartary && OrgAgendaModel.SelectedMeeting.MeetingType == 0)
                    {
                        //canParticipationBtnShow = true;

                        var am = (AgendaModel)ParticipantsListView.DataContext;
                        foreach (var item in am.ParticipantsList)
                        {
                            item.IsParticipationBtnVisible = Visibility.Visible;
                        }
                        ParticipantsListView.DataContext = null;
                        ParticipantsListView.DataContext = am;

                        LblParticipantsTimerDisplay.Text = Enableed;
                    }
                    _dispatcherTimer.Stop();

                    //DisplayTimerForParticipantsList();

                    #endregion
                }

                //if (((int)diff.TotalSeconds) == 0)
                //{
                //}
            }
            catch (Exception)
            {
            }
        }

        //enable this if you want to make the participans list readonly when meeting ends
        //it also notify before 10 mins onwards
        /*private void DispatcherTimer1_Tick1()
        {
            if (((int)diff1.TotalMinutes) <= 9)  //This means 10, not to worry  :)
            {
                lbl_ParticipantsTimerDisplay.Text = readonlyin + diff1.Minutes.ToString("00") + ":" + diff1.Seconds.ToString("00");
            }

            if (((int)diff1.TotalSeconds) == 0)
            {
                AgendaModel am = (AgendaModel)ParticipantsListView.DataContext;
                foreach (var item in am.ParticipantsList)
                {
                    item.IsParticipationBtnEnabled = false;
                }
                ParticipantsListView.DataContext = null;
                ParticipantsListView.DataContext = am;

                lbl_ParticipantsTimerDisplay.Text = "readonly";
                dispatcherTimer1.Stop();
            }

            diff1 = diff1.Subtract(new TimeSpan(0, 0, 1));
        }*/
        /*private void VisibleIcon(Image image)
        {
            /*if (image == null)
            {
                img_TimerDisplayRedIcon.Visibility = Visibility.Collapsed;
                img_TimerDisplayGreenIcon.Visibility = Visibility.Collapsed;
                return;
            }
            if (image == img_TimerDisplayRedIcon)
            {
                img_TimerDisplayRedIcon.Visibility = Visibility.Visible;
                img_TimerDisplayGreenIcon.Visibility = Visibility.Collapsed;
                return;
            }
            if (image == img_TimerDisplayGreenIcon)
            {
                img_TimerDisplayRedIcon.Visibility = Visibility.Collapsed;
                img_TimerDisplayGreenIcon.Visibility = Visibility.Visible;
                return;
            }*/

        private async Task LoadParticipantsListView(ObservableCollection<MemberModel> list)
        {
            try
            {
                if (list == null || list.Count <= 0) return;

                foreach (var item in list)
                {
                    var item1 = item;
                    await
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                            async () =>
                            {
                                item1.ProfilePicPath = await BasePage.UpdateProfilePic(item1.MemberId);
                                item1.ListItemIndex = item1.MemberId;

                                if (!Global.IsBoardSecrartary ||
                                    OrgAgendaModel.SelectedMeeting.MeetingType == (int)MeetingType.Circular)
                                {
                                    item1.IsParticipationBtnVisible = Visibility.Collapsed;
                                    item.StatusColorCode = new SolidColorBrush(Colors.Gray);
                                }
                            });

                    //NOTE: added to the DAO
                    //NOTE: IsActive false people will be readonly
                    //item.ListItemBgColor = "Transparent";
                    //if (item.IsActive != (int)BoardMemberIsActive.Active)
                    //{
                    //item.ListItemBgColor = "LightGray";
                    //item.StatusColorCode = new SolidColorBrush(Colors.Gray);
                    //}

                    /*switch (item.AttendanceStatus)
                    {
                        #region Conditions  (ParticipantsListView_SelectionChanged also has another list)

                        case (int)BoardMemberParticipationStatus.Present:
                            item.StatusText = BoardMemberParticipationStatus.Present.ToString();
                            item.StatusColorCode = new SolidColorBrush(Colors.Green);
                            break;

                        case (int)BoardMemberParticipationStatus.Excused:
                            item.StatusText = BoardMemberParticipationStatus.Excused.ToString();
                            item.StatusColorCode = new SolidColorBrush(Colors.OrangeRed);
                            break;

                        case (int)BoardMemberParticipationStatus.ConCall:
                            item.StatusText = BoardMemberParticipationStatus.ConCall.ToString();
                            item.StatusColorCode = new SolidColorBrush(Colors.DeepSkyBlue);
                            break;

                        case (int)BoardMemberParticipationStatus.Absent:
                            item.StatusText = BoardMemberParticipationStatus.Absent.ToString();
                            item.StatusColorCode = new SolidColorBrush(Colors.DarkGray);
                            break;

                        #endregion
                    }*/
                }
            }
            catch (Exception)
            {
            }
        }

        private void LoadParticipantsListViewViaSync(ObservableCollection<MemberModel> updatedParticipantsList)
        {
            try
            {
                foreach (var updatedItem in updatedParticipantsList)
                {
                    //Find the updated item on old list
                    var oldItem = OrgAgendaModel.ParticipantsList.FirstOrDefault(x => x.MemberId == updatedItem.MemberId);

                    //Check old item has pending changes
                    var val = AttendanceChanges.FirstOrDefault(x => x.Key == oldItem.MemberId);
                    if (val.Key == 0) //Status not changed
                    {
                        updatedItem.IsParticipationBtnVisible = oldItem.IsParticipationBtnVisible;
                        updatedItem.ListItemBgColor = oldItem.ListItemBgColor;
                        updatedItem.ListItemIndex = oldItem.ListItemIndex;
                        updatedItem.StatusColorCode = oldItem.StatusColorCode;
                        updatedItem.ProfilePicPath = oldItem.ProfilePicPath;
                    }
                    else //Status changed
                    {
                        updatedItem.StatusColorCode = oldItem.StatusColorCode;
                        updatedItem.ListItemIndex = oldItem.ListItemIndex;
                        updatedItem.ListItemBgColor = oldItem.ListItemBgColor;
                        updatedItem.ProfilePicPath = oldItem.ProfilePicPath;
                    }
                }

                OrgAgendaModel.ParticipantsList = updatedParticipantsList;

                #region MyRegion

                /*foreach (var item in list)
                {
                    var val = AttendanceChanges.Where(x => x.Key == item.MemberId).FirstOrDefault();
                    if (val.Key == 0) //not available
                    {
                        item.AttendanceStatus = item.AttendanceStatus - 1;
                        if (item.AttendanceStatus < 0) item.AttendanceStatus = 4;

                    }


                    if (item.IsSyncInProgressRing == Visibility.Visible)
                    {
                        item.AttendanceStatus = item.AttendanceStatus - 1;
                        if (item.AttendanceStatus < 0) item.AttendanceStatus = 4;
                    }
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                        {
                            item.ListItemIndex = item.MemberId;

                            item.ProfilePicPath = await BasePage.UpdateProfilePic(item.MemberId);

                            if (Global.IsBoardSecrartary && canParticipationBtnShow && orgAgendaModel.SelectedMeeting.MeetingType == (int)MeetingType.Meeting)
                            {
                                item.IsParticipationBtnVisible = Visibility.Visible;
                            }
                            else
                            {
                                item.IsParticipationBtnVisible = Visibility.Collapsed;
                            }
                        });
                }
                
                if (ParticipantsListView.Items.Count <= 0)
                    return;

                for (int i = 0; i < list.Count; i++)
                {
                    ParticipantsListView.SelectedIndex = -1;
                    ParticipantsListView.SelectedIndex = i;
                }*/

                #endregion
            }
            catch (Exception)
            {
            }
        }


        private void btn_ParticipantStatus_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var button = sender as Button;
                if (button == null || button.Content == null) return;

                IsParticipantsListUpdated = true;
                var selectedIndex = Convert.ToInt32(button.Tag.ToString());

                #region MyRegion Commented

                //int memberId = Convert.ToInt32(button.CommandParameter);

                /*if (memberId == Global.UserId)  //If the same user, then individual participation combobox need to update as well
                {
                    string status = button.Content.ToString();

                    #region Switch
                    BoardMemberParticipationStatus enumValue = (BoardMemberParticipationStatus)Utility.GetEnumValue(typeof(BoardMemberParticipationStatus), status);

                    switch (enumValue)
                    {
                        case BoardMemberParticipationStatus.None:
                            enumValue = BoardMemberParticipationStatus.Accepted;
                            break;

                        case BoardMemberParticipationStatus.Accepted:
                            enumValue = BoardMemberParticipationStatus.Declined;
                            break;

                        case BoardMemberParticipationStatus.Declined:
                            enumValue = BoardMemberParticipationStatus.Tentative;
                            break;

                        case BoardMemberParticipationStatus.Tentative:
                            enumValue = BoardMemberParticipationStatus.ConCall;
                            break;

                        case BoardMemberParticipationStatus.ConCall:
                            enumValue = BoardMemberParticipationStatus.None;
                            break;
                    }
                    #endregion

                    //BoardMemberIndividualParticipationStatus val = (BoardMemberIndividualParticipationStatus)((int)enumValue);

                    //int ss = orgAgendaModel.IndividualParticipationStatusList.FindIndex(x => x.StartsWith(val.ToString()));
                    //cmb_IndividualParticipationStatus.SelectedIndex = -1;
                    //cmb_IndividualParticipationStatus.SelectedIndex = ss;
                    return;
                }*/

                #endregion

                ParticipantsListView.SelectedIndex = -1;
                ParticipantsListView.SelectedIndex =
                    OrgAgendaModel.ParticipantsList.IndexOf(
                        OrgAgendaModel.ParticipantsList.FirstOrDefault(a => a.MemberId == selectedIndex));
            }
            catch (Exception)
            {
            }
        }

        private void ParticipantsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ParticipantsListView.SelectedIndex == -1) return;

                var container = (sender as ListView).ContainerFromItem(e.AddedItems.First());
                if (container == null) return;
                var presenter = VisualTreeHelper.GetChild(container, 0);
                if (presenter == null) return;
                var currentGrid = VisualTreeHelper.GetChild(presenter, 0) as Grid;
                if (currentGrid == null) return;

                var prgWaitRingGrid =
                    FindVisualChildren<Grid>(currentGrid).FirstOrDefault(tb => tb.Name.Equals("prg_WaitRingGrid"));

                var waitBar =
                    FindVisualChildren<ProgressBar>(currentGrid).FirstOrDefault(tb => tb.Name.Equals("prg_WaitRing"));

                var colorLineGrid =
                    FindVisualChildren<Grid>(currentGrid).FirstOrDefault(tb => tb.Name.Equals("grd_ColorLine"));

                foreach (
                    var tb in
                        FindVisualChildren<Button>(currentGrid).Where(tb => tb.Name.Equals("btn_ParticipantStatus")))
                {
                    string state; //tb.Content.ToString();

                    var mmModel = OrgAgendaModel.ParticipantsList[ParticipantsListView.SelectedIndex];
                    switch (mmModel.AttendanceStatus)
                    {
                        case 0:
                            state = BoardMemberParticipationStatus.Absent.ToString();
                            break;
                        case 1:
                            state = BoardMemberParticipationStatus.Present.ToString();
                            break;
                        case 2:
                            state = BoardMemberParticipationStatus.Excused.ToString();
                            break;
                        case 3:
                            state = BoardMemberParticipationStatus.ConCall.ToString();
                            break;
                        default:
                            state = BoardMemberParticipationStatus.Absent.ToString();
                            break;
                    }

                    if (IsParticipantsListUpdated)
                    {
                        mmModel.IsSyncInProgressRing = Visibility.Visible;
                        prgWaitRingGrid.Visibility = Visibility.Visible;
                        waitBar.Visibility = Visibility.Visible;

                        #region Switch

                        var enumValue =
                            (BoardMemberParticipationStatus)
                                Utility.GetEnumValue(typeof(BoardMemberParticipationStatus), state);
                        int index; //NOTE: -1 is very important. Don't change
                        switch (enumValue)
                        {
                            case BoardMemberParticipationStatus.Absent:
                                var sTat0 = BoardMemberParticipationStatus.Present.ToString();
                                index = (int)BoardMemberParticipationStatus.Present;
                                var brush0 = new SolidColorBrush(Colors.Green);

                                colorLineGrid.Background = brush0;
                                tb.Content = sTat0;
                                tb.Background = brush0;

                                mmModel.StatusText = sTat0;
                                mmModel.AttendanceStatus = index;
                                mmModel.StatusColorCode = brush0;
                                break;

                            case BoardMemberParticipationStatus.Present:
                                var sTat1 = BoardMemberParticipationStatus.Excused.ToString();
                                index = (int)BoardMemberParticipationStatus.Excused;
                                var brush1 = new SolidColorBrush(Colors.OrangeRed);

                                colorLineGrid.Background = brush1;
                                tb.Content = sTat1;
                                tb.Background = brush1;

                                mmModel.StatusText = sTat1;
                                mmModel.AttendanceStatus = index;
                                mmModel.StatusColorCode = brush1;
                                break;

                            case BoardMemberParticipationStatus.Excused:
                                var sTat2 = BoardMemberParticipationStatus.ConCall.ToString();
                                index = (int)BoardMemberParticipationStatus.ConCall;
                                var brush2 = new SolidColorBrush(Colors.DeepSkyBlue);

                                colorLineGrid.Background = brush2;
                                tb.Content = sTat2;
                                tb.Background = brush2;

                                mmModel.StatusText = sTat2;
                                mmModel.AttendanceStatus = index;
                                mmModel.StatusColorCode = brush2;
                                break;

                            case BoardMemberParticipationStatus.ConCall:
                                var sTat4 = BoardMemberParticipationStatus.Absent.ToString();
                                index = (int)BoardMemberParticipationStatus.Absent;
                                var brush4 = new SolidColorBrush(Colors.DarkGray);

                                colorLineGrid.Background = brush4;
                                tb.Content = sTat4;
                                tb.Background = brush4;

                                mmModel.StatusText = sTat4;
                                mmModel.AttendanceStatus = index;
                                mmModel.StatusColorCode = brush4;
                                break;
                        }

                        #endregion

                        AddOrUpdateAttandanceChanges(mmModel);
                    }
                    else
                    {
                        if (mmModel.IsSyncInProgressRing == Visibility.Visible) return;

                        mmModel.IsSyncInProgressRing = Visibility.Collapsed;
                        prgWaitRingGrid.Visibility = Visibility.Collapsed;
                        waitBar.Visibility = Visibility.Collapsed;
                    }
                    break;
                }

                var actionData = OrgAgendaModel.ParticipantsList.Aggregate("",
                    (current, memModel) => current + (memModel.MemberId + "#" + memModel.AttendanceStatus + "#"));
                actionData = actionData.TrimEnd('#');

                var changesOnly = AttendanceChanges.Aggregate("",
                    (current, item) => current + (item.Key + "#" + item.Value + "#"));
                changesOnly = changesOnly.TrimEnd('#');

                LogModel.MemberId = Global.UserId;
                LogModel.MeetingId = OrgAgendaModel.SelectedMeeting.MeetingId;
                LogModel.PaperId = null;
                LogModel.Action = ApplicationConstants.LogActions.UpdateMeetingPresence;
                LogModel.Info = changesOnly;
                LogModel.Data = actionData;
            }
            catch (Exception)
            {
            }
        }

        private void AddOrUpdateAttandanceChanges(MemberModel mmModel)
        {
            try
            {
                var val = AttendanceChanges.FirstOrDefault(x => x.Key == mmModel.MemberId);
                if (val.Key == 0)
                    AttendanceChanges.Add(mmModel.MemberId, mmModel.AttendanceStatus);
                else
                    AttendanceChanges[val.Key] = mmModel.AttendanceStatus;
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        ///     Public updated logmodel will write to the database
        /// </summary>
        /// <returns></returns>
        private async Task WriteMemberAttendanceToLogTable()
        {
            try
            {
                if (IsParticipantsListUpdated && !String.IsNullOrWhiteSpace(LogModel.Data) &&
                    !String.IsNullOrWhiteSpace(LogModel.Info))
                {
                    var rdm = await _agendaService.WriteMemberAttendanceToLogTable(LogModel);
                    if (!rdm.IsError)
                    {
                        IsParticipantsListUpdated = false;
                        LogModel.Data = "";
                        LogModel.Info = "";
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        //NOTE: Can't apply try catch when yield used - Suren
        private IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj == null) yield break;
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                var child = VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }

                foreach (var childOfChild in FindVisualChildren<T>(child))
                {
                    yield return childOfChild;
                }
            }
        }

        private async void cmb_IndividualParticipationStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (CmbIndividualParticipationStatus.SelectedIndex == -1) return;
                if (CmbIndividualParticipationStatus.SelectedIndex == _initialCmbSelectedIndex) return;
                if (CmbIndividualParticipationStatus.SelectedIndex == _loggedInMemberParticipantStat) return;

                var ldm = new LogDataModel
                {
                    MeetingId = OrgAgendaModel.SelectedMeeting.MeetingId,
                    PaperId = null,
                    Action = ApplicationConstants.LogActions.UpdateIndividualPresence,
                    Data = CmbIndividualParticipationStatus.SelectedIndex.ToString()
                };

                //NOTE: Also writes to the Meetings table's MemberIndividualAttendance col as well
                var rdm = await _agendaService.WriteIndividualPartcipStatusToLogTable(ldm);

                if (rdm.IsError)
                {
                    CmbIndividualParticipationStatus.SelectedIndex = _initialCmbSelectedIndex;
                    await _dialogService.ShowMessage("Something went wrong");
                }
                else
                {
                    OrgAgendaModel.SelectedMeeting.MemberIndividualAttendance = rdm.Data.ToString();
                    _initialCmbSelectedIndex = CmbIndividualParticipationStatus.SelectedIndex;
                }
            }
            catch (Exception)
            {
            }
        }

        #endregion

        #region Display Ui

        private void ResetGrids()
        {
            DiscussionItemGrid.Visibility = Visibility.Collapsed;
            WidgetsGrid.Visibility = Visibility.Collapsed;
            VideoItemsGrid.Visibility = Visibility.Collapsed;
            BoardPaperGrid.Visibility = Visibility.Collapsed;
            MiddleSliderBtn.Visibility = Visibility.Collapsed;
            PaperMeetingTogglePanel.Visibility = Visibility.Collapsed;
        }

        private void ResetTopAppbar()
        {
            //Top appbar
            AppBarButtonSearch.Visibility = Visibility.Collapsed;
            AppBarToggleButtonBookmark.Visibility = Visibility.Collapsed;
            AppBarButtonViewPage.Visibility = Visibility.Collapsed;
            AppBarButtonViewMode.Visibility = Visibility.Collapsed;
            AppBarButtonOutline.Visibility = Visibility.Collapsed;
            AppBarButtonAnnotateVersions.Visibility = Visibility.Collapsed;
            AppBarButtonSharing.Visibility = Visibility.Collapsed;
            AppBarButtonEdit.Visibility = Visibility.Collapsed;
        }

        private void EnableTopAppbar()
        {
            AppBarButtonSearch.Visibility = Visibility.Visible;
            AppBarToggleButtonBookmark.Visibility = Visibility.Visible;
            AppBarButtonViewPage.Visibility = Visibility.Visible;
            AppBarButtonViewMode.Visibility = Visibility.Visible;
            AppBarButtonOutline.Visibility = Visibility.Visible;
            AppBarButtonAnnotateVersions.Visibility = Visibility.Visible;
            AppBarButtonSharing.Visibility = Visibility.Visible;
            AppBarButtonEdit.Visibility = Visibility.Visible;
        }

        private void ResetBottomAppbar()
        {
            MeetingNoteButton.Visibility = Visibility.Collapsed;

            //Bottom right appbar
            PaperCommentsButton.Visibility = Visibility.Collapsed;
            ApprovalButton.Visibility = Visibility.Collapsed;
            SharePaperButton.Visibility = Visibility.Collapsed;
            InfoButton.Visibility = Visibility.Collapsed;

            AgendaSearchButton.Visibility = Visibility.Collapsed;
            MeetingCommentButton.Visibility = Visibility.Collapsed;

            ThumbnailSliderBdr.Visibility = Visibility.Collapsed;
            //NOTE: If user switch between paper and meeting info using the toggle button
            //when watching a video, this code will pause the video
            MediaElementForAgenda.Pause();
        }

        private void DisplayInitialView()
        {
            try
            {
                ResetGrids();
                WidgetsGrid.Visibility = Visibility.Visible;

                ResetTopAppbar();

                ResetBottomAppbar();

                //Bottom left appbar
                MeetingsButton.Visibility = Visibility.Visible;
                AgendaSearchButton.Visibility = Visibility.Visible;
                MeetingCommentButton.Visibility = Visibility.Visible;
                PastPapersButton.Visibility = Visibility.Visible;

                if (OrgAgendaModel.SelectedMeeting.MeetingType == (int)MeetingType.Meeting)
                    MeetingNoteButton.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void DisplaySmallPaperView()
        {
            try
            {
                if (GlobalSelectdAgendaItem.DocType == (byte)DocumentType.AudioVideo)
                {
                    MediaItemMaip();
                    return;
                }

                ResetGrids();
                MiddleSliderBtn.Visibility = Visibility.Visible;
                BoardPaperGrid.Visibility = Visibility.Visible;
                PaperMeetingTogglePanel.Visibility = Visibility.Visible;

                EnableTopAppbar();

                ResetBottomAppbar();
                //PreviousPaperButton.Visibility = Visibility.Collapsed;
                MeetingsButton.Visibility = Visibility.Visible;
                AgendaSearchButton.Visibility = Visibility.Visible;
                MeetingCommentButton.Visibility = Visibility.Visible;
                PastPapersButton.Visibility = Visibility.Visible;
                if (OrgAgendaModel.SelectedMeeting.MeetingType == (int)MeetingType.Meeting)
                    MeetingNoteButton.Visibility = Visibility.Visible;

                //Bottom right appbar
                PaperCommentsButton.Visibility = Visibility.Visible;
                ApprovalButton.Visibility = Visibility.Visible;
                SharePaperButton.Visibility = Visibility.Visible;
                InfoButton.Visibility = Visibility.Visible;
                //NextPaperButton.Visibility = Visibility.Collapsed;

                if (GlobalSelectdAgendaItem.DocType != null && (!Global.IsBoardSecrartary &&
                                                                (byte)GlobalSelectdAgendaItem.DocType !=
                                                                (byte)DocumentType.BoardPaper))
                {
                    ApprovalButton.Visibility = Visibility.Collapsed;
                }

                ThumbnailSliderBdr.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void DisplayDiscussionPaperView()
        {
            try
            {
                ResetGrids();
                DiscussionItemGrid.Visibility = Visibility.Visible;
                PaperMeetingTogglePanel.Visibility = Visibility.Visible;

                MediaElementForAgenda.Pause();

                ResetTopAppbar();

                ResetBottomAppbar();
                //PreviousPaperButton.Visibility = Visibility.Collapsed;
                MeetingsButton.Visibility = Visibility.Visible;
                AgendaSearchButton.Visibility = Visibility.Visible;
                MeetingCommentButton.Visibility = Visibility.Visible;
                PastPapersButton.Visibility = Visibility.Visible;
                if (OrgAgendaModel.SelectedMeeting.MeetingType == (int)MeetingType.Meeting)
                    MeetingNoteButton.Visibility = Visibility.Visible;

                //Bottom right appbar
                PaperCommentsButton.Visibility = Visibility.Visible;
                ApprovalButton.Visibility = Visibility.Visible;
                InfoButton.Visibility = Visibility.Visible;
                //NextPaperButton.Visibility = Visibility.Collapsed;

                if (!Global.IsBoardSecrartary)
                    ApprovalButton.Visibility = Visibility.Collapsed;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void MediaItemMaip()
        {

            ResetGrids();
            VideoItemsGrid.Visibility = Visibility.Visible;

            ResetBottomAppbar();
            MediaElementForAgenda.Play();
            PaperCommentsButton.Visibility = Visibility.Visible;
            MiddleSliderBtn.Visibility = Visibility.Visible;
        }

        private void DisplayPaperFullScreenView()
        {
            try
            {
                if (GlobalSelectdAgendaItem.DocType == (byte)DocumentType.AudioVideo)
                {
                    MediaItemMaip();
                    return;
                }

                ResetGrids();
                BoardPaperGrid.Visibility = Visibility.Visible;
                MiddleSliderBtn.Visibility = Visibility.Visible;

                EnableTopAppbar();

                ResetBottomAppbar();
                //PreviousPaperButton.Visibility = Visibility.Collapsed;
                MeetingsButton.Visibility = Visibility.Visible;
                PastPapersButton.Visibility = Visibility.Visible;

                //Bottom right appbar
                PaperCommentsButton.Visibility = Visibility.Visible;
                ApprovalButton.Visibility = Visibility.Visible;
                SharePaperButton.Visibility = Visibility.Visible;
                InfoButton.Visibility = Visibility.Visible;
                //NextPaperButton.Visibility = Visibility.Visible;

                if (GlobalSelectdAgendaItem.DocType != null && (!Global.IsBoardSecrartary &&
                                                                (byte)GlobalSelectdAgendaItem.DocType !=
                                                                (byte)DocumentType.BoardPaper))
                {
                    ApprovalButton.Visibility = Visibility.Collapsed;
                }

                ThumbnailSliderBdr.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
            }
        }

        private void DisplayVideoPlayBackView()
        {
            try
            {
                ResetGrids();
                VideoItemsGrid.Visibility = Visibility.Visible;
                MiddleSliderBtn.Visibility = Visibility.Visible;
                PaperMeetingTogglePanel.Visibility = Visibility.Visible;

                ResetTopAppbar();

                ResetBottomAppbar();
                MeetingsButton.Visibility = Visibility.Visible;
                AgendaSearchButton.Visibility = Visibility.Visible;
                MeetingCommentButton.Visibility = Visibility.Visible;
                PastPapersButton.Visibility = Visibility.Visible;
                if (OrgAgendaModel.SelectedMeeting.MeetingType == (int)MeetingType.Meeting)
                    MeetingNoteButton.Visibility = Visibility.Visible;

                //Bottom right appbar
                PaperCommentsButton.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
                throw;
            }
        }

        double gridSlideSpeedInSec = 0.3;
        private async void MiddleSlider_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsCollapsed)  // Split view
                {
                    IsCollapsed = false;

                    _pdfViewCtrl.Width = _collapsedWidth;

                    var val = AgendaItemGridCol1.ActualWidth * -1;
                    var moveSb = new Storyboard();
                    var moveTransform = new TranslateTransform();
                    AgendaItemGrid.RenderTransform = moveTransform;
                    var duration = new Duration(TimeSpan.FromSeconds(gridSlideSpeedInSec));
                    var myDoubleAnimationX = new DoubleAnimation { Duration = duration, From = val, To = 0 };
                    moveSb.Children.Add(myDoubleAnimationX);
                    Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                    Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                    moveSb.Begin();

                    MiddleSliderBtn.Content = new SymbolIcon(Symbol.ClosePane);

                    DisplaySmallPaperView();
                    PaperMeetingTogglePanel.Visibility = Visibility.Visible;

                    AdjustPdfViewerReverse(val);
                }
                else  // Paper fullscreen view
                {
                    IsCollapsed = true;

                    _pdfViewCtrl.Width = Window.Current.Bounds.Width - MiddleBarGrd.ActualWidth - 50;

                    var val = AgendaItemGridCol1.ActualWidth * -1;
                    var moveSb = new Storyboard();
                    var moveTransform = new TranslateTransform();
                    AgendaItemGrid.RenderTransform = moveTransform;
                    var duration = new Duration(TimeSpan.FromSeconds(gridSlideSpeedInSec));
                    var myDoubleAnimationX = new DoubleAnimation { Duration = duration, To = val };
                    moveSb.Children.Add(myDoubleAnimationX);
                    Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                    Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                    moveSb.Begin();

                    MiddleSliderBtn.Content = new SymbolIcon(Symbol.OpenPane);

                    DisplayPaperFullScreenView();
                    PaperMeetingTogglePanel.Visibility = Visibility.Collapsed;

                    AdjustPdfViewer(val);
                }

                await ExportAnnotations();
            }
            catch (Exception)
            {
            }
        }

        // Paper fullscreen view
        private void AdjustPdfViewer(double val)
        {
            try
            {
                var grid = BoardPaperGrid;
                if (GlobalSelectdAgendaItem.DocType == (byte)DocumentType.AudioVideo)
                {
                    grid = VideoItemsGrid;
                }

                var moveSb = new Storyboard();
                var moveTransform = new TranslateTransform();
                grid.RenderTransform = moveTransform;
                var duration = new Duration(TimeSpan.FromSeconds(gridSlideSpeedInSec));
                var myDoubleAnimationX = new DoubleAnimation { Duration = duration, To = val };
                moveSb.Children.Add(myDoubleAnimationX);
                Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                moveSb.Begin();

                grid.Margin = new Thickness(0, 0, val, 0);
            }
            catch (Exception)
            {
            }
        }

        // Paper split view
        private void AdjustPdfViewerReverse(double val)
        {
            try
            {
                var grid = BoardPaperGrid;
                if (GlobalSelectdAgendaItem.DocType == (byte)DocumentType.AudioVideo)
                {
                    grid = VideoItemsGrid;
                }

                var moveSb = new Storyboard();
                var moveTransform = new TranslateTransform();
                grid.RenderTransform = moveTransform;
                var duration = new Duration(TimeSpan.FromSeconds(gridSlideSpeedInSec));
                var myDoubleAnimationX = new DoubleAnimation { Duration = duration, From = val, To = 0 };
                moveSb.Children.Add(myDoubleAnimationX);
                Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                moveSb.Begin();
                //int ss = 0;

                grid.Margin = new Thickness(0, 0, 0, 0);
            }
            catch (Exception)
            {
            }
        }

        #endregion

        #region Paper / Media Loading

        private async Task<bool> LoadPdfDocumentToViewer(IBuffer pdfFile, InputMessageDialog dialog)
        {
            try
            {
                //GC.Collect();
                //Deallocate resources used for pdf viewing
                //this.PDFViewCtrl.CloseDoc();
                //if (doc != null)
                //{
                //    doc.Destroy();
                //    doc.Dispose();
                //}

                _pdfDoc = await GetPdfDocAsync(pdfFile);

                _param = new NavigationParameter(_pdfDoc, null, null, false);
                if (_param != null)
                {
                    if (!_pdfDoc.InitStdSecurityHandler(""))
                    {
                        _oTaskCompletionSource = new TaskCompletionSource<bool>();
                        if (dialog != null) dialog.HideAsync();
                        HandlePassword();
                        var result = await _oTaskCompletionSource.Task;
                        if (!result) //PDF Password Failed
                        {
                            //NOTE: If you select the same item when the password dialog is open, without the below
                            //item will not open for the second time.
                            GlobalSelectdAgendaItem = null;
                            DisplayInitialView();
                            return false;
                        }
                    }
                    else
                    {
                        CommonPaperLoading();
                    }
                    await UpdateViewedPaper();
                }
            }
            catch (Exception)
            {
                //Don't throw any exception. This is fine.
            }
            return true;
        }

        private void CommonPaperLoading()
        {
            try
            {
                _pdfViewCtrl.SetDoc(_pdfDoc);

                #region MyRegion

                //this.PDFFile = param.File;
                //this.Stream = param.Stream;

                /*if (param.ReadOnly)
                {
                    AppBarButton_Save.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }
                else
                {
                    // This will automatically save the document every 30 seconds, provided it has been modified.
                    //_AutoSaveHelper = new Utilities.AutoSaveHelper(30);
                    //_AutoSaveHelper.PDFDoc = param.Doc;
                }*/

                #endregion

                if (_param.Doc.GetPageCount() > 0) //Org val 4
                {
                    ThumbnailSlider.PDFViewCtrl = _pdfViewCtrl;
                }
                else
                {
                    BottomAppBar = null;
                    _thumbSliderAppBar = null;
                }
            }
            catch (Exception)
            {
                //var pdfNetEx = new PDFNetException(ex.HResult);
                throw;
            }
        }

        private async Task LoadMediaToViewer(IBuffer mediaFile)
        {
            try
            {
                MediaElementForAgenda.Stop();
                MediaElementForAgenda.Source = null;

                if (mediaFile != null)
                {
                    var stream = await Utility.ToStream(mediaFile);
                    MediaElementForAgenda.SetSource(stream, "");

                    DisplayVideoPlayBackView();

                    await UpdateViewedPaper();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region Agenda

        //Agenda Heading Click
        private async void txt_HeadingItem_Tapped(object sender, TappedRoutedEventArgs e)
        {
            try
            {
                await ExportAnnotations();

                GlobalSelectdAgendaItem = null;
                DisplayInitialView();
            }
            catch (Exception)
            {
            }
        }

        //Agenda Item Click
        private async void btn_AgendaItem_Click(object sender, RoutedEventArgs e)
        {
            var docTypeName = "";
            InputMessageDialog imdlg = null;
            try
            {
                PasswordDialog_PasswordEntered(null);
                MeetingInfoPanelShowHideToggle.IsOn = false;
                DetachAppBars();

                var agendaItem = sender as Button;

                await ExportAnnotations();

                var agParam = (AgendaItem)agendaItem.CommandParameter;
                //If same agenda item click, return from the method
                if (GlobalSelectdAgendaItem != null && GlobalSelectdAgendaItem.Id == (agParam.Id) &&
                    GlobalSelectdAgendaItem.VersionId == (agParam.VersionId) &&
                    agParam.DownloadStatus == (int)PaperDownloadStatuses.Downloded)
                {
                    await ImportAnnotations();
                    return;
                }

                if (agParam.DownloadStatus == (int)PaperDownloadStatuses.Downloding)
                {
                    docTypeName = BasePage.GetInstance().GetDocTypeName(agParam.DocType);
                    await _dialogService.ShowMessage(docTypeName + "downloading in progress");
                    return;
                }

                GlobalSelectdAgendaItem = agParam;
                AddCommentsViewModel.AgendaItemId = GlobalSelectdAgendaItem.Id;
                docTypeName = BasePage.GetInstance().GetDocTypeName(GlobalSelectdAgendaItem.DocType);

                //NOTE: DiscussionItems dont have papers but user can comment on it
                if (GlobalSelectdAgendaItem.DocType != null &&
                    (byte)GlobalSelectdAgendaItem.DocType == (byte)DocumentType.DiscussionItem)
                {
                    DisplayDiscussionPaperView();
                    await UpdateViewedPaper();

                    if (Global.IsBoardSecrartary)
                        await CreateApprovalMenuFlyOut();

                    return;
                }

                if (agParam.DownloadStatus == (int)PaperDownloadStatuses.NotDownloded)
                {
                    AgendaItemForceDownloadEvt(PaperDownloadStatuses.Downloding, GlobalSelectdAgendaItem.Id);
                }

                //NOTE:
                //Duplicated on AgendaPage.xaml.cs and NewsAndSharedDocsPage.xaml.cs

                #region Paper Download or Load to View

                _isSaveOrgAnnotationFile = true;
                imdlg = new InputMessageDialog(docTypeName + "loading", Visibility.Collapsed, Visibility.Collapsed, true);
                imdlg.ShowAsync();

                //Check the db for download status and if its 1 and also check for the physical file.
                //if exist send the decrypted file else returns null
                var file =
                    await
                        _agendaService.GetPdfDocument(GlobalSelectdAgendaItem.Id, GlobalSelectdAgendaItem.MeetingId,
                            (byte)GlobalSelectdAgendaItem.DocType, GlobalSelectdAgendaItem.VersionId);
                imdlg.HideAsync();

                if (file == null) //Download the doc
                {
                    if (Global.UserForceWentOffline)
                    {
                        await _dialogService.ShowMessage("You are offline");
                        GlobalSelectdAgendaItem = null;
                        return;
                    }

                    await DownloadPaper();
                }
                else //Load the pdf to the viewer
                {
                    //https://social.msdn.microsoft.com/forums/windowsapps/en-us/2c7b290a-dd84-44a7-b3f4-29abc55fe010/how-to-show-dialog-with-textbox-control
                    imdlg = new InputMessageDialog(docTypeName + "loading", Visibility.Collapsed, Visibility.Collapsed,
                        true);
                    imdlg.ShowAsync();

                    DisplaySmallPaperView();
                    await CreateApprovalMenuFlyOut();

                    bool result = false;
                    if (GlobalSelectdAgendaItem.DocType == (byte)DocumentType.AudioVideo)
                        await LoadMediaToViewer(file);
                    else
                    {
                        result = await LoadPdfDocumentToViewer(file, imdlg);
                        if (!result) return;

                        await CreateAnnotatedVersionsMenuFlyOut();
                    }

                    //Paper loading time have to set the user approval stamp, because stamp is not an annotation
                    var givenBmApprovalFromDb = await _agendaService.GetAgendaItemApproval(GlobalSelectdAgendaItem.Id);
                    PaperStatus = Global.IsBoardSecrartary
                        ? ((PaperStatus)givenBmApprovalFromDb.Item1).ToString()
                        : ((DecisionStatus)givenBmApprovalFromDb.Item1).ToString();

                    if (givenBmApprovalFromDb.Item1 != 0 &&
                        GlobalSelectdAgendaItem.DocType != (byte)DocumentType.AudioVideo) //Skip pending status
                    {
                        await
                            BasePage.GetInstance()
                                .SetApprovalStamp(_param.Doc, _pdfViewCtrl, PaperStatus, GlobalSelectdAgendaItem);
                    }
                }

                await LoadBookmarks();
                await ImportAnnotations();

                #endregion
            }
            catch (Exception)
            {
                DisplayInitialView();
                if (GlobalSelectdAgendaItem != null &&
                    (GlobalSelectdAgendaItem.DownloadStatus != (int)PaperDownloadStatuses.Downloded))
                    AgendaItemForceDownloadEvt(PaperDownloadStatuses.DownloadError, GlobalSelectdAgendaItem.Id);

                GlobalSelectdAgendaItem = null;
                _dialogService.ShowMessage(docTypeName + "encountered an error");
            }
            finally
            {
                AttachAppBars();
                if (imdlg != null) imdlg.HideAsync();
            }
        }

        private async Task DownloadPaper()
        {
            try
            {
                var dlg = new DownloadingUserControl();
                var rdm = await dlg.ShowAsync(0, GlobalSelectdAgendaItem, null);

                if (!rdm.IsError)
                {
                    var pdfFile = (byte[])rdm.Data;
                    //Write the encrypted file to storage and update the database
                    await
                        _syncService.SaveEncryptedFile(pdfFile, GlobalSelectdAgendaItem.Id,
                            GlobalSelectdAgendaItem.VersionId);

                    //Read the above file decrypt it and return
                    var decFile =
                        await
                            _agendaService.GetPdfDocument(GlobalSelectdAgendaItem.Id, GlobalSelectdAgendaItem.MeetingId,
                                (byte)GlobalSelectdAgendaItem.DocType, GlobalSelectdAgendaItem.VersionId);
                    if (decFile == null)
                    {
                        AgendaItemForceDownloadEvt(PaperDownloadStatuses.NotDownloded, GlobalSelectdAgendaItem.Id);
                        GlobalSelectdAgendaItem = null;
                        await _dialogService.ShowMessage(ResourceHandler.Get("err_102"));
                        return;
                    }

                    DisplaySmallPaperView();
                    //ShowHidePaperCommentBtnEvt("Show PaperComment Button");

                    AgendaItemForceDownloadEvt(PaperDownloadStatuses.Downloded, GlobalSelectdAgendaItem.Id);

                    if (GlobalSelectdAgendaItem.DocType == (byte)DocumentType.AudioVideo)
                        await LoadMediaToViewer(decFile);
                    else
                    {
                        bool result = await LoadPdfDocumentToViewer(decFile, null);
                        if (!result) return;

                        await CreateAnnotatedVersionsMenuFlyOut();
                    }
                }
                else
                {
                    AgendaItemForceDownloadEvt(PaperDownloadStatuses.NotDownloded, GlobalSelectdAgendaItem.Id);
                    GlobalSelectdAgendaItem = null;

                    //NOTE: -1 means its canceled by the user intentionally
                    if (!rdm.ErrorCode.Equals("-1"))
                        await _dialogService.ShowMessage(rdm.ErrorMessage);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        //Comments Button Click
        private async void Btn_AgendaItemComments_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var agendaItemBtn = sender as Button;
                var agendaItem = (AgendaItem)agendaItemBtn.CommandParameter;
                AddCommentsViewModel.AgendaItemId = agendaItem.Id;

                var meetingIds = new List<int>();
                var agendItemIds = new List<int> { agendaItem.Id };
                await
                    _commentService.UpdateViewedComments(ApplicationConstants.LogActions.UpdateViewedPaperComments,
                        meetingIds, agendItemIds);
                agendaItem.IsCommentsAvailable = Visibility.Collapsed;

                ViewPaperComments();
            }
            catch (Exception)
            {
            }
        }

        //Share Annotate button Click
        private void btn_AgendaItemSharedAnnotate_Click(object sender, RoutedEventArgs e)
        {
        }

        private async Task UpdateViewedPaper()
        {
            try
            {
                var result =
                    await
                        _agendaService.UpdateViewedPaper(Global.UserId, GlobalSelectdAgendaItem.Id,
                            GlobalSelectdAgendaItem.VersionId);
                if (result)
                {
                    var t = new Tuple<AgendaItem, bool>(GlobalSelectdAgendaItem, true);
                    AgendaItemClickPaperStatusSideIconEvtHandler(t, EventArgs.Empty);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region Meeting Info Panel Show Hide Toggle

        private void MeetingInfoUimanipulation(MeetingModel meetingModel)
        {
            try
            {
                meetingModel.MeetingAtVisibility = Visibility.Visible;
                meetingModel.MeetingRoomVisibility = Visibility.Visible;

                if (String.IsNullOrWhiteSpace(meetingModel.Venue))
                {
                    meetingModel.MeetingRoomVisibility = Visibility.Collapsed;
                }
                if (String.IsNullOrWhiteSpace(meetingModel.Address))
                {
                    meetingModel.MeetingAtVisibility = Visibility.Collapsed;
                }

                if (meetingModel.MeetingType == (int)MeetingType.Circular)
                {
                    meetingModel.ParticipationStatusVisibility = Visibility.Collapsed;
                    meetingModel.MeetingInfoHeading = "circular info";
                    meetingModel.ParticipantsInfoHeading = "members";
                }
                else
                {
                    meetingModel.ParticipationStatusVisibility = Visibility.Visible;
                    meetingModel.MeetingInfoHeading = "meeting info";
                    meetingModel.ParticipantsInfoHeading = "participants";
                }
            }
            catch (Exception)
            {
            }
        }

        private async void MeetingInfoDisplay(MeetingModel meetingModel)
        {
            try
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    MeetingAtTextBlock.Visibility = Visibility.Visible;
                    MeetingRoomGrid.Visibility = Visibility.Visible;

                    //TODO:
                    //OrganizerTextBlock.Text = ??

                    if (String.IsNullOrWhiteSpace(meetingModel.Address))
                        MeetingAtTextBlock.Visibility = Visibility.Collapsed;
                    else
                        AddressTextBlock.Text = meetingModel.Address;

                    if (String.IsNullOrWhiteSpace(meetingModel.Venue))
                        MeetingRoomGrid.Visibility = Visibility.Collapsed;
                    else
                        VenueTextBlock.Text = meetingModel.Venue;

                    DescriptionTextBlock.Text = meetingModel.Description;
                });
            }
            catch (Exception)
            {
            }
        }

        /*private void MeetingInfoPanelShow_Btn_Checked(object sender, RoutedEventArgs e)
        {
            DisplayInitialView();
        }

        private void MeetingInfoPanelShow_Btn_Unchecked(object sender, RoutedEventArgs e)
        {
            if (GlobalSelectdAgendaItem.DocType == (byte) DocumentType.DiscussionItem)
                DisplayDiscussionPaperView();
            else
            {
                DisplaySmallPaperView();
            }
        }*/

        private void PaperMeetingToggle_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var togg = sender as Button;
                var isOn = Convert.ToBoolean(togg.Tag);

                if (MeetingInfoPanelShowHideToggle.IsOn == isOn)
                    return;

                MeetingInfoPanelShowHideToggle.IsOn = isOn;
            }
            catch (Exception)
            {
            }
        }

        private void MeetingInfoPanelShowHide_Toggle_Toggled(object sender, RoutedEventArgs e)
        {
            try
            {
                switch (MeetingInfoPanelShowHideToggle.IsOn) //True: Meeting info | False: Paper info
                {
                    case true: // Meeting info
                        DisplayInitialView();
                        break;
                    case false: // Paper info
                        if (GlobalSelectdAgendaItem.DocType == (byte)DocumentType.DiscussionItem)
                            DisplayDiscussionPaperView();
                        else
                            DisplaySmallPaperView();
                        break;
                }
                PaperMeetingTogglePanel.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
            }
        }

        #endregion

        #region Top Appbar

        private void DetachAppBars()
        {
            TopAppBar = null;
            BottomAppBar = null;
        }

        private void AttachAppBars()
        {
            if (TopAppBar == null)
            {
                TopAppBar = _topAppBar;
            }
            if (BottomAppBar == null)
            {
                BottomAppBar = _thumbSliderAppBar;
            }
        }

        private void CloseAppBars()
        {
            try
            {
                if (BottomAppBar != null)
                {
                    if (!_asm.GetAppBarPinnedStatus())
                        BottomAppBar.IsOpen = false;
                }
                if (TopAppBar != null)
                {
                    TopAppBar.IsOpen = false;
                }
            }
            catch (Exception)
            {
            }
        }

        private void TopAppBar_Opened(object sender, object e)
        {
            try
            {
                FindTextDialog.CloseDialog();
                OutlineDialog.CloseDialog();
                CloseThumbnailsViewer();

                AppBarToggleButtonBookmark.IsChecked = ValidateBookmark();
            }
            catch (Exception)
            {
            }
        }

        private void TopAppBar_Closed(object sender, object e)
        {
        }


        private async void EditAppBarButton_Clicked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!_isSaveOrgAnnotationFile)
                {
                    await _dialogService.ShowMessage("Annotations are not available for sent or received annotations");
                    return;
                }

                AnnotationToolbarDialog.OpenDialog();
                CloseAppBars();

                //Timer to auto save annotations
                if (_dispatcherTimerForAutoSave != null)
                {
                    _dispatcherTimerForAutoSave.Stop();
                    _dispatcherTimerForAutoSave.Interval = new TimeSpan(0, 0, AutoSaveTimeInSec); //1 second
                    _dispatcherTimerForAutoSave.Start();
                }
                else
                {
                    _dispatcherTimerForAutoSave = new DispatcherTimer();
                    _dispatcherTimerForAutoSave.Tick += (s, args) => DispatcherTimer_TickForAutoSave();
                    _dispatcherTimerForAutoSave.Interval = new TimeSpan(0, 0, AutoSaveTimeInSec); //1 second
                    _dispatcherTimerForAutoSave.Start();
                }
            }
            catch (Exception)
            {
            }
        }

        private async void AppBarButton_Sharing_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await ExportAnnotations();

                _mUserControl = new AnnotationShareUserControl();
                _mUserControl.ShowPopup(GlobalSelectdAgendaItem);
                CloseAppBars();
            }
            catch (Exception)
            {
            }
        }

        //NOTE: Load original paper
        private async void OriginalPaperLoading_ButtonClick(object sender, EventArgs e)
        {
            try
            {
                var paperModel = await _agendaService.GetOriginalPaperVersionByPaperId(GlobalSelectdAgendaItem.Id);
                //if (GlobalSelectdAgendaItem.VersionId == paperModel.VersionId)
                //{
                //isSaveOrgAnnotationFile = true;
                //await ImportAnnotations();
                //return;
                //}

                _isSaveOrgAnnotationFile = true;
                GlobalSelectdAgendaItem.VersionId = paperModel.VersionId;
                await LoadPaperCommon(true, false);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private async void SentPapers_UserControlButtonClick(object sender, EventArgs e)
        {
            try
            {
                var paperModel = sender as PaperModel;
                if (paperModel == null) return;

                GlobalSelectdAgendaItem.Id = paperModel.PaperId;
                GlobalSelectdAgendaItem.VersionId = paperModel.VersionId;

                await LoadPaperCommon(false, false);
                if (_param != null)
                {
                    _isSaveOrgAnnotationFile = false;
                    await ImportSharedAnnotations(_param.Doc, paperModel, ShareType.Sent);
                }
            }
            catch (Exception)
            {
            }
        }

        private async void ReceivedPapers_UserControlButtonClick(object sender, EventArgs e)
        {
            try
            {
                var paperModel = sender as PaperModel;
                if (paperModel == null) return;

                GlobalSelectdAgendaItem.Id = paperModel.PaperId;
                GlobalSelectdAgendaItem.VersionId = paperModel.VersionId;

                await LoadPaperCommon(false, true);

                if (_param != null)
                {
                    _isSaveOrgAnnotationFile = false;
                    await ImportSharedAnnotations(_param.Doc, paperModel, ShareType.Received);
                }
            }
            catch (Exception)
            {
            }
        }

        private async Task ImportSharedAnnotations(PDFDoc doc, PaperModel paperModel, ShareType type)
        {
            InputMessageDialog imdlg = null;
            try
            {
                imdlg = new InputMessageDialog("Annotation file is loading", Visibility.Collapsed, Visibility.Collapsed,
                    true);
                imdlg.ShowAsync();
                var anoteDoc1 = await BasePage.GetInstance().ImportSharedAnnotations(doc, paperModel, type);
                imdlg.HideAsync();

                if (anoteDoc1 == null)
                {
                    imdlg = new InputMessageDialog("Annotation file is downloading", Visibility.Collapsed,
                        Visibility.Collapsed, true);
                    imdlg.ShowAsync();
                    var rdm = await _syncService.AnnotationDownload(paperModel);
                    imdlg.HideAsync();

                    if (String.IsNullOrWhiteSpace(rdm.ErrorMessage))
                    {
                        imdlg = new InputMessageDialog("Annotation file is loading", Visibility.Collapsed,
                            Visibility.Collapsed, true);
                        imdlg.ShowAsync();
                        await BasePage.GetInstance().ImportSharedAnnotations(doc, paperModel, type);
                        imdlg.HideAsync();
                    }
                    else
                    {
                        await _dialogService.ShowMessage(rdm.ErrorMessage);
                        return;
                    }
                }

                _pdfViewCtrl.Update();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (imdlg != null) imdlg.HideAsync();
            }
        }

        private void SearchAppBarButton_Clicked(object sender, RoutedEventArgs e)
        {
            try
            {
                FindTextDialog.OpenDialog();
                CloseAppBars();
            }
            catch (Exception)
            {
            }
        }

        private void OutlineAppBarButton_Clicked(object sender, RoutedEventArgs e)
        {
            try
            {
                OutlineDialog.OpenDialog();
                CloseAppBars();
                FlyoutDialogEnabled();
            }
            catch (Exception)
            {
            }
        }

        private void ViewPageAppBarButton_Click(object sender, RoutedEventArgs e)
        {
            var vPage = sender as Button;
            var val = vPage.CommandParameter.ToString();

            switch (val)
            {
                case "fw":
                    _pdfViewCtrl.SetPageViewMode(PDFViewCtrlPageViewMode.e_fit_width);
                    _pdfViewCtrl.SetPageRefViewMode(PDFViewCtrlPageViewMode.e_fit_width);
                    break;

                case "fp":
                    _pdfViewCtrl.SetPageViewMode(PDFViewCtrlPageViewMode.e_fit_page);
                    _pdfViewCtrl.SetPageRefViewMode(PDFViewCtrlPageViewMode.e_fit_page);
                    break;
            }

            CloseAppBars();
        }

        private async void LogoutButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DetachAppBars();
                await BasePage.LogoutButton_Click(_navigationService, _dialogService, _authService);
                AttachAppBars();
            }
            catch (Exception)
            {
            }
        }


        private async Task CreateAnnotatedVersionsMenuFlyOut()
        {
            try
            {
                ClearItemsOfAnnotateVersionsMenuFlyOut();

                //TODO: find versions here and load it, select the current paper as well
                var paperVersions =
                    await
                        _agendaService.GetPaperVersionsByPaperId(GlobalSelectdAgendaItem.Id,
                            GlobalSelectdAgendaItem.VersionId);
                if (paperVersions == null || paperVersions.Count <= 0) return;

                if (paperVersions.Count == 1)
                {
                    var mn = new ToggleMenuFlyoutItem
                    {
                        Text = "Original (" +
                               ((DateTime)(paperVersions[0].DocCreatedDateTime)).ToString(Utility.GetDateTimeFormat()) +
                               ")",
                        IsChecked = true,
                        Tag = paperVersions[0].VersionId
                    };
                    mn.Click += AnnotateVersionsMenuItem_Click;
                    AnnotateVersionsMenuFlyOut.Items.Add(mn);
                    return;
                }

                var count = paperVersions.Count;
                for (var i = 0; i < count; i++)
                {
                    var paper = paperVersions[i];
                    var mn = new ToggleMenuFlyoutItem
                    {
                        Text = "Version " + paper.VersionInfo + ".0 (" +
                               ((DateTime)(paper.DocCreatedDateTime)).ToString(Utility.GetDateTimeFormat()) + ")"
                    };
                    mn.Click += AnnotateVersionsMenuItem_Click;
                    mn.Tag = paper.VersionId;
                    mn.IsChecked = false;

                    if (GlobalSelectdAgendaItem.VersionId == paper.VersionId)
                    {
                        mn.Text = "Original (" +
                                  ((DateTime)(paper.DocCreatedDateTime)).ToString(Utility.GetDateTimeFormat()) + ")";
                        mn.IsChecked = true;
                    }
                    AnnotateVersionsMenuFlyOut.Items.Add(mn);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void ClearItemsOfAnnotateVersionsMenuFlyOut()
        {
            var items = AnnotateVersionsMenuFlyOut.Items.ToList();
            if (AnnotateVersionsMenuFlyOut.Items.Count > 0)
            {
                foreach (var item in items)
                {
                    AnnotateVersionsMenuFlyOut.Items.Remove(item);
                }
            }
        }

        private async void AnnotateVersionsMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CloseAppBars();
                ClearTicksOfAnnotateVersionsMenuFlyOut();

                var item = sender as ToggleMenuFlyoutItem;
                item.IsChecked = true;

                var verId = Convert.ToInt32(item.Tag);
                if (verId == GlobalSelectdAgendaItem.VersionId) return;

                GlobalSelectdAgendaItem.VersionId = verId;
                await LoadPaperCommon(true, false);
            }
            catch (Exception)
            {
            }
        }

        private void ClearTicksOfAnnotateVersionsMenuFlyOut()
        {
            var items = AnnotateVersionsMenuFlyOut.Items.ToList();
            if (AnnotateVersionsMenuFlyOut.Items.Count <= 0) return;
            foreach (var menuItem in items.Select(item => item as ToggleMenuFlyoutItem))
            {
                menuItem.IsChecked = false;
            }
        }

        #endregion

        #region Bottom Appbar

        private void MeetingsButton_Click(object sender, RoutedEventArgs e)
        {
            BasePage.MeetingsButton_Click(_navigationService);
        }

        private void AgendaSearchButton_Click(object sender, RoutedEventArgs e)
        {
            var mdm = new MessageDataModel { MessageData = true };
            var message = new NotificationMessage<MessageDataModel>(mdm, MessageCodes.SEARCH_FLYOUT);
            Messenger.Default.Send(message);
        }

        private void AgendaSearchPaneCloseButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var moveSb = new Storyboard();
                var moveTransform = new TranslateTransform();
                SearchFlyout.RenderTransform = moveTransform;
                var duration = new Duration(TimeSpan.FromSeconds(0.3));
                var myDoubleAnimationX = new DoubleAnimation();
                var ease = new CubicEase { EasingMode = EasingMode.EaseIn };
                myDoubleAnimationX.EasingFunction = ease;
                myDoubleAnimationX.Duration = duration;
                myDoubleAnimationX.From = 0;
                myDoubleAnimationX.To = 500;
                moveSb.Children.Add(myDoubleAnimationX);
                Storyboard.SetTarget(myDoubleAnimationX, moveTransform);
                Storyboard.SetTargetProperty(myDoubleAnimationX, "X");
                moveSb.Begin();
            }
            catch (Exception)
            {
            }
        }

        private async void MeetingCommentButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var meetingIds = new List<int>();
                var agendItemIds = new List<int>();

                meetingIds.Add(OrgAgendaModel.SelectedMeeting.MeetingId);

                await
                    _commentService.UpdateViewedComments(
                        ApplicationConstants.LogActions.UpdateViewedMeetingComments, meetingIds, agendItemIds);

                AddCommentsViewModel.CommentType = 1; //Meeting Comments
                AddCommentsViewModel.CommentTypeHeading = "meeting comments";
                _navigationService.NavigateTo(typeof(AddCommentsPage));

                var mdm = new MessageDataModel { MessageData = 1 };
                var message = new NotificationMessage<MessageDataModel>(mdm, MessageCodes.GET_COMMENTS);
                Messenger.Default.Send(message);
            }
            catch (Exception)
            {
            }
        }

        private async void PaperCommentsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var meetingIds = new List<int>();
                var agendItemIds = new List<int> { GlobalSelectdAgendaItem.Id };

                await
                    _commentService.UpdateViewedComments(ApplicationConstants.LogActions.UpdateViewedPaperComments,
                        meetingIds, agendItemIds);
                GlobalSelectdAgendaItem.IsCommentsAvailable = Visibility.Collapsed;
                ViewPaperComments();
            }
            catch (Exception)
            {
            }
        }

        private void ViewPaperComments()
        {
            AddCommentsViewModel.CommentType = 0; //Paper Comments
            AddCommentsViewModel.CommentTypeHeading = "paper comments";
            _navigationService.NavigateTo(typeof(AddCommentsPage));

            var mdm = new MessageDataModel { MessageData = 0 };
            var message = new NotificationMessage<MessageDataModel>(mdm, MessageCodes.GET_COMMENTS);
            Messenger.Default.Send(message);
        }

        private void PastPapersButton_Click(object sender, RoutedEventArgs e)
        {
            BasePage.PastPapersButton_Click(_navigationService);
        }


        private void PreviousPaperButton_Click(object sender, RoutedEventArgs e)
        {
            //TODO: do this
        }

        private void NextPaperButton_Click(object sender, RoutedEventArgs e)
        {
            //TODO: do this
        }


        public async Task GetMeetingNote(string meetingNote, object sender)
        {
            try
            {
                AttachAppBars();
                var button = sender as Button;

                if (!button.Content.Equals("Cancel"))
                {
                    var modifiedMeetingNote = meetingNote.Replace("\r\n",
                        ApplicationConstants.MeetingNoteNewLineChar.ToString());
                    //Replace new line character with unique character. it used in backend to replace that with </br>

                    var rslt =
                        await
                            _meetingService.AddMeetingNote(Global.UserId, OrgAgendaModel.SelectedMeeting.MeetingId,
                                modifiedMeetingNote);

                    if (rslt)
                    {
                        OrgAgendaModel.SelectedMeeting.MeetingNote = meetingNote;
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void MeetingNoteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DetachAppBars();

                var mUserControl = new MeetingNoteDialogUserControl(OrgAgendaModel.SelectedMeeting.MeetingNote);
                mUserControl.ShowPopup();
            }
            catch (Exception)
            {
            }
        }


        private void InfoButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DetachAppBars();

                var mUserControl = new PaperInfoUserControl();
                mUserControl.ShowPopup(GlobalSelectdAgendaItem);
            }
            catch (Exception)
            {
            }
        }

        public void ClosePaperInfo(string note, object sender)
        {
            try
            {
                AttachAppBars();
            }
            catch (Exception)
            {
            }
        }


        private async void SharePaperMenuFlyoutItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CloseAppBars();

                var mfItem = sender as MenuFlyoutItem;

                //Email annotated comments
                if (mfItem.Tag.Equals("1"))
                {
                    #region MyRegion

                    await ExportAnnotations();
                    var stat = await CheckForAnnotations();
                    if (!stat) return;

                    _isPaperEmailingAllowed = false;
                    _isCommentsEmailingAllowed = true;
                    DataTransferManager.ShowShareUI();
                    return;

                    #endregion
                }

                //Email annotated paper
                if (mfItem.Tag.Equals("2"))
                {
                    #region MyRegion

                    await ExportAnnotations();
                    var stat = await CheckForAnnotations();
                    if (!stat) return;

                    _isPaperEmailingAllowed = true;
                    _isCommentsEmailingAllowed = false;
                    DataTransferManager.ShowShareUI();
                    return;

                    #endregion
                }

                //Print paper
                if (mfItem.Tag.Equals("3"))
                {
                    #region MyRegion

                    if (ActualWidth >= 768)
                    {
                        //https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh465204.aspx  (Quickstart: Printing from your app (XAML))
                        //Register document for printing (PDFTron)
                        var docTitle = GlobalSelectdAgendaItem.Name;
                        _pdfPrintManager.RegisterForPrintingContract(_param.Doc, docTitle);

                        await PrintManager.ShowPrintUIAsync();
                    }
                    else
                    {
                        await _dialogService.ShowMessage("Snap mode printing is not allowed");
                    }
                    return;

                    #endregion
                }

                //Send to OneNote
                if (mfItem.Tag.Equals("4"))
                {
                    var result =
                        await
                            _dialogService.ShowMessageYesNo("Are you sure you want to send this document to OneNote?",
                                DefaultButtonCommand.No);
                    if (!result) return;

                    DetachAppBars();
                    await
                        OneNoteHelper.OneNoteProcess(GlobalSelectdAgendaItem, _dialogService, OrgAgendaModel, _param);
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                AttachAppBars();
            }
        }

        private async Task<bool> CheckForAnnotations()
        {
            try
            {
                var annotFile = await BasePage.GetAnnotationFile(GlobalSelectdAgendaItem);
                if (annotFile == null)
                {
                    await _dialogService.ShowMessage("Please annotate the paper before sharing");
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public async Task GetPaperApprovalComment(string comment)
        {
            try
            {
                AttachAppBars();

                var stat = Global.IsBoardSecrartary
                    ? Utility.GetPaperStatus(PaperStatus)
                    : Utility.GetPaperDecisionStatus(PaperStatus);

                if (!string.IsNullOrEmpty(comment))
                {
                    comment = stat.ToString() + ApplicationConstants.Seperator + comment;
                    await
                        _agendaService.AddPaperApprovals(ApplicationConstants.LogActions.UpdateUserApprovals,
                            comment, GlobalSelectdAgendaItem.Id);
                }
                else
                {
                    await
                        _agendaService.AddPaperApprovals(ApplicationConstants.LogActions.UpdateUserApprovals,
                            stat.ToString(), GlobalSelectdAgendaItem.Id);
                }

                _pdfViewCtrl.SetDoc(
                    await
                        BasePage.GetInstance()
                            .SetApprovalStamp(_param.Doc, _pdfViewCtrl, PaperStatus, GlobalSelectdAgendaItem));
                _pdfViewCtrl.GotoFirstPage();
                _pdfViewCtrl.Update();
            }
            catch (Exception)
            {
            }
        }

        private async void ApprovalMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (GlobalSelectdAgendaItem.DocType != (byte)DocumentType.DiscussionItem)
                {
                    await ExportAnnotations();
                }

                var finalApprovalsbyBs = new List<byte> { 1, 2, 3 };
                var isFinalApprovalGiven = GlobalSelectdAgendaItem.PaperStatus != null &&
                                           finalApprovalsbyBs.Contains((byte)GlobalSelectdAgendaItem.PaperStatus);

                if (isFinalApprovalGiven && Global.IsBoardSecrartary)
                {
                    foreach (
                        var menuItem in
                            ApprovalMenuFlyOut.Items.Select(item => item as ToggleMenuFlyoutItem)
                                .Where(menuItem => menuItem.IsChecked))
                    {
                        menuItem.IsChecked = false;
                    }

                    var mn = sender as ToggleMenuFlyoutItem;
                    mn.IsChecked = true;
                    PaperStatus = mn.Text;

                    var dialog = new ContentDialog();
                    dialog.ShowPopup();
                    DetachAppBars();
                }
                else if (!isFinalApprovalGiven)
                {
                    foreach (
                        var menuItem in
                            ApprovalMenuFlyOut.Items.Select(item => item as ToggleMenuFlyoutItem)
                                .Where(menuItem => menuItem.IsChecked))
                    {
                        menuItem.IsChecked = false;
                    }

                    var mn = sender as ToggleMenuFlyoutItem;
                    mn.IsChecked = true;
                    PaperStatus = mn.Text;

                    var dialog = new ContentDialog();
                    dialog.ShowPopup();
                    DetachAppBars();
                }
                else
                {
                    foreach (var menuItem in ApprovalMenuFlyOut.Items.Select(item => item as ToggleMenuFlyoutItem))
                    {
                        menuItem.IsChecked = false;
                    }
                    await
                        _dialogService.ShowMessage(
                            "Paper has been finalized. You can not change paper approval status now");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private async Task CreateApprovalMenuFlyOut()
        {
            try
            {
                var items = ApprovalMenuFlyOut.Items.ToList();
                if (ApprovalMenuFlyOut.Items.Count > 0)
                {
                    foreach (var item in items)
                    {
                        ApprovalMenuFlyOut.Items.Remove(item);
                    }
                }

                string givenBmApproval = null;

                var approvalOptions = await _agendaService.GetAprovalOptions(OrgAgendaModel.SelectedMeeting.MeetingType);

                if (GlobalSelectdAgendaItem != null) //Not pending
                {
                    var givenBmApprovalFromDb = await _agendaService.GetAgendaItemApproval(GlobalSelectdAgendaItem.Id);
                    givenBmApproval = Global.IsBoardSecrartary
                        ? ((PaperStatus)givenBmApprovalFromDb.Item1).ToString()
                        : ((DecisionStatus)givenBmApprovalFromDb.Item1).ToString();
                }

                if (!string.IsNullOrEmpty(approvalOptions) && GlobalSelectdAgendaItem != null)
                {
                    var approvalOptionsArrFromDb = Global.IsBoardSecrartary
                        ? approvalOptions.Split(',').Reverse().Take(3).Reverse().ToArray()
                        : approvalOptions.Split(',').Take(5).ToArray();

                    var approvalOptionsMapperArr = Global.IsBoardSecrartary
                        ? ApplicationConstants.ApprovalOptionsForMeetingsAndCirculars.Split(',').Reverse().
                            Take(GlobalSelectdAgendaItem.DocType == (byte)DocumentType.BoardPaper ? 3 : 1)
                            .Reverse()
                            .ToArray()
                        : ApplicationConstants.ApprovalOptionsForMeetingsAndCirculars.Split(',').Take(5).ToArray();

                    var cir = approvalOptionsArrFromDb.Length;
                    for (var i = 0; i < cir; i++)
                    {
                        if (approvalOptionsArrFromDb[i] != "1" || approvalOptionsMapperArr.Count() <= i) continue;

                        var mn = new ToggleMenuFlyoutItem { Text = approvalOptionsMapperArr[i] };
                        mn.Click += ApprovalMenuItem_Click;
                        mn.IsChecked = mn.Text.Replace(" ", string.Empty).Equals(givenBmApproval);
                        mn.IsChecked = mn.Text.Replace(" ", string.Empty).Equals(givenBmApproval);
                        ApprovalMenuFlyOut.Items.Add(mn);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void PinnedAppBarButton_Checked(object sender, RoutedEventArgs e)
        {
            BasePage.PinnedAppBarButton_Checked(PinnedAppBarButton, _asm);
        }

        private void PinnedAppBarButton_Unchecked(object sender, RoutedEventArgs e)
        {
            BasePage.PinnedAppBarButton_UnChecked(PinnedAppBarButton, _asm);
        }

        #endregion

        #region Bookmarks

        private async void AppBarToggleButton_Bookmark_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                var currPage = _pdfViewCtrl.GetCurrentPage();
                AppBarToggleButtonBookmark.Label = "Remove Bookmark";

                //NOTE: Already have a bookmark, so dont add another one
                if (ValidateBookmark())
                {
                    return;
                }

                foreach (var item in _bookmarks)
                {
                    var foo = _pdfDoc.GetFirstBookmark().Find(item.Value);
                    foo.Delete();
                }

                _bookmarks.Add(currPage, Page + currPage); //Newest bookmard added to the list
                _bookmarks = _bookmarks.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                foreach (var item in _bookmarks)
                {
                    var rootBookmark = Bookmark.Create(_pdfDoc, item.Value);
                    _pdfDoc.AddRootBookmark(rootBookmark);
                    rootBookmark.SetColor(0, 1, 0);
                    rootBookmark.SetAction(Action.CreateGoto(Destination.CreateFit(_pdfDoc.GetPage(item.Key))));
                }

                await SaveBookmarks();
            }
            catch (Exception)
            {
            }
        }

        private async void AppBarToggleButton_Bookmark_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                var currPage = _pdfViewCtrl.GetCurrentPage();
                AppBarToggleButtonBookmark.Label = "Add Bookmark";

                //NOTE: If no bookmark then nothing to be removed
                if (!ValidateBookmark())
                {
                    return;
                }

                var foo = _pdfDoc.GetFirstBookmark().Find(Page + currPage);
                foo.Delete();
                _bookmarks.Remove(currPage);
                await SaveBookmarks();
            }
            catch (Exception)
            {
            }
        }

        private bool ValidateBookmark()
        {
            try
            {
                var currPage = _pdfViewCtrl.GetCurrentPage();

                var foo = _pdfDoc.GetFirstBookmark().Find(Page + currPage);
                return foo.IsValid();
            }
            catch (Exception)
            {
                return false;
            }
        }

        private async Task<bool> SaveBookmarks()
        {
            try
            {
                var fileName = GlobalSelectdAgendaItem.Id + "_" + Global.UserId + "_" +
                               GlobalSelectdAgendaItem.VersionId;
                return await _agendaService.SaveBookmarks(_bookmarks, fileName);
            }
            catch (Exception)
            {
                return false;
            }
        }

        private async Task<bool> LoadBookmarks()
        {
            _bookmarks = null;
            _bookmarks = new Dictionary<int, string>();
            try
            {
                var fileName = GlobalSelectdAgendaItem.Id + "_" + Global.UserId + "_" +
                               GlobalSelectdAgendaItem.VersionId;
                _bookmarks = await _agendaService.LoadBookmarks(fileName);

                foreach (var item in _bookmarks)
                {
                    var rootBookmark = Bookmark.Create(_pdfDoc, item.Value);
                    _pdfDoc.AddRootBookmark(rootBookmark);
                    rootBookmark.SetColor(0, 1, 0);
                    rootBookmark.SetAction(Action.CreateGoto(Destination.CreateFit(_pdfDoc.GetPage(item.Key))));
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion

        #region Goto Page

        private void GotoTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                BasePage.GetInstance().GotoTextBox_TextChanged(GotoTextBox, GotoButton, _pdfViewCtrl);
            }
            catch (Exception)
            {
            }
        }

        private void GotoTextBox_KeyUp(object sender, KeyRoutedEventArgs e)
        {
            try
            {
                if (e.Key != VirtualKey.Enter) return;

                BasePage.GetInstance().GotoTextBox_TextChanged(GotoTextBox, GotoButton, _pdfViewCtrl);
                if (GotoButton.IsEnabled)
                    BasePage.GetInstance().GotoButton_Click(_pdfViewCtrl, GotoTextBox);
            }
            catch (Exception)
            {
            }
        }

        private void GotoButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BasePage.GetInstance().GotoButton_Click(_pdfViewCtrl, GotoTextBox);
            }
            catch (Exception)
            {
            }
        }

        #endregion

        #region Bing Maps

        private void LoadMap(Map map)
        {
            try
            {
                //https://msdn.microsoft.com/en-us/library/dn456475.aspx
                var pushpin = new Pushpin { Text = "S" };

                var longitude = Double.Parse(OrgAgendaModel.SelectedMeeting.Longitude);
                var latitude = Double.Parse(OrgAgendaModel.SelectedMeeting.Latitude);
                map.Center = new Location(latitude, longitude);

                MapLayer.SetPosition(pushpin, new Location(latitude, longitude));

                map.ZoomLevel = 10;
                map.Children.Add(pushpin);

                TxtMapErrorMsg.Visibility = Visibility.Collapsed;
                BtnMapFullScreen.Visibility = Visibility.Visible;
                map.Visibility = Visibility.Visible;

                map.UpdateLayout();
            }
            catch (Exception)
            {
                TxtMapErrorMsg.Visibility = Visibility.Visible;
                BtnMapFullScreen.Visibility = Visibility.Collapsed;
                map.Visibility = Visibility.Collapsed;
            }
        }

        /*private void RefreshMap(Map map)
        {
            map.UpdateLayout();
            var c = map.Center;
            c.Latitude += 0.00001;
            map.SetView(c, map.ZoomLevel);
        }*/

        private void btn_MapFullScreen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LoadMap(MyMapLarge);

                if (!MapPopup.IsOpen)
                {
                    RootPopupBorder.Width = Window.Current.Bounds.Width * 0.8;
                    RootPopupBorder.Height = Window.Current.Bounds.Height * 0.7;

                    MapPopup.HorizontalOffset = (Window.Current.Bounds.Width - (Window.Current.Bounds.Width * 0.8)) * -1;
                    MapPopup.VerticalOffset = (Window.Current.Bounds.Height - (Window.Current.Bounds.Height * 0.7)) * -1;

                    MapPopup.IsOpen = true;
                }
            }
            catch (Exception)
            {
            }
        }

        #endregion

        private void WidgetSwitchBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (GridW1.Visibility == Visibility.Collapsed)
                {
                    GridW1.Visibility = Visibility.Visible;
                    StkPnl1.Visibility = Visibility.Visible;

                    StkPnl2.Visibility = Visibility.Collapsed;
                    ParticipantsListView.Visibility = Visibility.Collapsed;
                }
                else
                {
                    GridW1.Visibility = Visibility.Collapsed;
                    StkPnl1.Visibility = Visibility.Collapsed;

                    StkPnl2.Visibility = Visibility.Visible;
                    ParticipantsListView.Visibility = Visibility.Visible;
                }
            }
            catch (Exception)
            {
            }
        }
    }
}